Reputation: 13
I tried to convert users input from string to int
by casting each character to int
and multiply by its corresponding exponential. Everything works correctly till the point I need to assign the result value to a int
variable. It always one less than the correct value when the assigned value is between 100 and 1000.
i.e. int k=0; k+=100;
But printing k shows 99. But k+=1000
works fine.
The solution I found is to change the order of multiplicand and multiplier, but the cause to this situation is still unknown.
string k_input;
cin >> k_input;
int k = 0;
for (int i = 0; i < k_input.length(); i++)
{
cout << (k_input[i] - '0') << " " << pow(10, (k_input.length() - i) - 1) << endl;
k += (k_input[i] - '0') * pow(10, k_input.length() - i - 1);
}
i.e. By inputting 123, output should be 123, but it shows 122 instead.
And inputting 1221 shows 1221 as expected.
Upvotes: 1
Views: 350
Reputation: 51825
The problem, which may very well be compiler- and/or platform-specific, is almost certainly down to 'rounding' errors when converting the double
output of your calculation to an int
value. You can fix this by using the lround
function (defined in <cmath>
):
k += lround((k_input[i] - '0') * pow(10, k_input.length() - i - 1));
Incidentally, turning on compiler warnings will highlight issues like this! For your code, in Visual Studio, I was shown:
warning C4244: '+=': conversion from 'double' to 'int', possible loss of data
Upvotes: 1