Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ceil function returns the wrong number

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

#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 doubles and the result has decimal.
After that, ceil() can come into play and deal with the decimals.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading