Reputation: 163
My code is printing 192 for the input 100 (which is the desired result). But when I submit it on the online judge, it shows that the output of my program for the input 100 is 190. I copied and pasted the code in ideone.com and for input 100 I got result 192. I send it to my friend and on his PC the output is 190. But he also submitted the code onto ideone.com and got 192. What's the problem? Here's my code:
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
int main(){
lli in,ans = 0;
cin >> in;
if(in < 10)
cout << in << endl;
else{
lli digits = 0;
lli temp = in;
while(temp > 0){
digits++;
temp /= 10;
}
digits--;
while(in > 0){
//cout << "in: " << in << endl;
//cout << "digits: " << digits << endl;
ans += ((in - (pow(10,digits) - 1)) * (digits + 1));
in = in - (in - (pow(10,digits) - 1));
digits--;
if(in == 9){
ans+= 9;
break;
}
}
cout << ans << endl;
}
}
ideone link: http://ideone.com/zOvHzW
Why is this happening? I understand that it may be a compiler issue but what is really going on in here?
Upvotes: 3
Views: 902
Reputation: 238281
The problem is that std::pow
is not exact. It is an approximating algorithm. The floating point result that it returns may be off by some, very tiny amount.
When you convert the floating point number to an integer, you round it down by removing the fractional part. But, if the correct result would have been say 100
, and the error was -0.000...001
and therefore the result was 99.999...999
and you cut off the fractional part, then the integer that you get is 99.
How std::pow
is implemented is... specific to the implementer. Therefore the error may be one way in one compiler / computer, but the other way in another. That is why the result may differ.
Solution: Don't use std::pow
for integer calculation.
Workaround: Round the result to nearest integer first.
Upvotes: 1