I was trying to do this math operation and I use ceil()
for rounding the number. But I noticed that it gives the wrong result. The output of the operation is 48.90510949
and when we round the number it must be 49
. But instead of ceil()
gives 48
.
But when I give the number directly and without an operation, its true.
Here is the code:
#include <iostream>
#include <cmath>
using namespace std;
int main() {
int numberINT = ceil((67*100)/137);
float numberFLOAT = ceil((67*100)/137);
float numberFLOATsecond = ((67*100)/137);
float directNumber = 48.90510949;
cout<< numberINT<<endl;
cout<<numberFLOAT<<endl;
cout<< ceil(numberFLOATsecond)<<endl;
cout<<ceil(directNumber);
return 0;
}
Here is the output:
48
48
48
49
Any idea why is it gives this result, and a way to fix it?
>Solution :
Your ceil()
operations arrive too late.
Here you multiply and divide integers, which gives an integer result, then you pass this integer to the ceil()
function but there is no decimal to deal with.
Try ceil((67*100.0)/137);
for example; 100.0
is a double
then the multiplication and the division are performed with double
s and the result has decimal.
After that, ceil()
can come into play and deal with the decimals.