Reputation: 785
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?
Upvotes: 0
Views: 286
Reputation: 21900
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:
for each (char c in xs)
xsum = xsum + (c - '0');
for each (char c in ys)
ysum = ysum + (c - '0');
That should do it. In your code, this expression:
xsum = xsum + int(c);
Creates an int
which will hold the value c
. Since c
is a char and can be converted to an int, what you end up having is just an int
that contains the ASCII value of that character.
Upvotes: 4