Converting string of numbers to a number

The idea is pretty simple, but it the result is slightly incorrect, it gives 12343 instead of 12345. Any ideas why? It's driving my crazy..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <math.h>

using namespace std;

int main () {
string sNumber = "12345";
int iNumber = 0,index = 0;

for (short i = sNumber.length() - 1; i >= 0; i--){
iNumber += int(sNumber.at(i) - 48) * pow(10, index++);
cout << iNumber << endl;
}
cout << "The number is " << iNumber << endl;
return 0;
}
works fine on online compiler (cpp.sh)...

cpp.sh/4ntx

which compiler/ide are you using?
Last edited on
code bloks
it looks like its loosing 1 every two rounds, but once I gave it 1234567 it gave me back 1234566, so it lost 1, even though it had 7 rounds..
Last edited on
The pow function returns a float, so there's probably a rounding error happening.
Makes sens fg109, I added 0.5 on the end of the equation and the precision is back on.
Topic archived. No new replies allowed.