ceil() working improperly

The following code outputs 1, which is incorrect...

1
2
3
4
5
6
7
8
9
#include <iostream>
#include "math.h"
using namespace std;
 
int main()
{
        cout << ceil(3/2);
        return 0;
}


Isn't it supposed to output 2?
3 and 2 are both integers. Therefore 3/2 performs integer division, which results in 1
ceil(1) is 1


You probably wanted to do this:
ceil(3.0/2.0) which would perform floating point division, which would get you 1.5 -> 2.0
Integer division returns an integer.
when you divide two ints, they get rounded down, so 3/2 is 1.5, rounded down to 1, then you perform ceilon 1, which is 1/

also you should use <cmath> instead of "math.h" as cmath is wrapped in namespace std, and math.h isn't, not that it matters much when you're using namespace std; at the top of your file but anyway

1
2
3
4
5
6
7
8
#include <iostream>
#include <cmath>

int main()
{
    std::cout << std::ceil(3f/2f);
   return 0;
}

adding f to the end of a number tells the oompiler it should be processed as a float
Last edited on
Thanks.
any time
Topic archived. No new replies allowed.