When I execute this code the value of ans1, ans2 is 50002896 and 50005000.
I know there is some issues with ceil function but was not able to figure out the exact cause.
#include <bits/stdc++.h>
using namespace std;
int main()
{
long long ans1 = 0, ans2 = 0;
for (long long i = 1; i <= 10000; i++)
{
ans1 = ans1 + ceil((float)i / 1);
ans2 = ans2 + i;
}
cout << ans1 << " " << ans2 << endl;
}
The source of the problem is not the
ceilfunction, but rather that not all integers can be represented accuratly as floating point values.Some more info about floating point representation: Wikipedia IEEE 754. And a related post: Which is the first integer that an IEEE 754 float is incapable of representing exactly?.
The following code is a minimal demonstration of the same issue that causes your issue:
[Wrong] Output (expected: +1):
One approach would be to use
doubleinstead offloat.This will not solve the principle issue, but will make the range of representable integers a lot bigger:
Output:
Some side notes:
#include <bits/stdc++.h>- see here: Why should I not #include <bits/stdc++.h>?.using namespace std- see here Why is "using namespace std;" considered bad practice?.