I am trying to implement the following logic in C++. Here x and y are 2 variables of type integer. xs and ys are 2 variables of type string. I wish to convert integer to string and then proceed with the logic.
def isGoodPoint(x,y):
xs=str(abs(x))
ys=str(abs(y))
xsum=0
ysum=0
for c in xs:
xsum=xsum+int(c)
for c in ys:
ysum=ysum+int(c)
if xsum+ysum <=19:
return True
My C++ Source-code:
Somehow the conversion isn’t working and I am getting incorrect values in xs and ys. For example: if my function call is: isGoodPoint(0,0), then during debug mode values in xs and ys are something like 45 and 50 or some weird values. Actually xs and ys should have 0 as their values.
Am I missing something?
What you probably want is to add the digits of each number. What you are doing now is to add the ASCII value of each digit. If you want to add the digits, you have to substract the first digit’s ASCII value:
That should do it. In your code, this expression:
Creates an
intwhich will hold the valuec. Sincecis a char and can be converted to an int, what you end up having is just anintthat contains the ASCII value of that character.