+ 1
Why this code doesn't work?
3 Answers
+ 3
That was a tricky one.
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int p;
for(int k=0;k<10;k++){
p=round(pow(10,k));
cout << "p "<<p<<endl;
}
return 0;
}
Floating point numbers are not 100% accurate, so when it was outputting 9999 instead of 10000, it was because pow(k, 10) was returning 9999.999 or something like that instead of 10000.0. This wasnât corrected by casting to int because it casts by flooring, which always rounds down. There is a specific round() function in cmath to fix this though, so that would be better for casting from float or double to integer.
0
Thanks to you all! The point of my question was also that if you use a gcc compiler for example, this problem doesn't exist... It happens only with the compiler of SoloLearn.