ceil function question

Hi again everyone,

ceil(2.3) gives 3 as I expect.
ceil(3/2) gives 1 but I expected it to give 2 because 1.5 <= 2.

Could anyone explain this please? I tried all combinations of float(.) and double(.) such as ceil(float(2.3)) etc. and they gave the same results.

Thanks
Two comments

First:
- second division is integer division, the compiler did what you told it and now what you wanted.

Second:
I don't believe ceil is actually cross platform.
You may want to try something like:

-std::floor(-value) or something like that since floor is universally implemented.
3/2 = 1, because it is an integer division, so what it actually does is compute 3 / 2 and then use it as a parameter in your ceil call. Use ceil ((double) 3 / 2);

EDIT: Now I see where your problem probably is :) it is (double) ... not double (...).
Last edited on
Thank you, the (double) bit worked. :) Just as a bonus, what's the difference between double (.) and (double) and how does it influence the result?
Glad you got it working. :) The difference between double (...) and (double) is just the priority of operators. when you have double (3 / 2), it first divides 3 by 2 (which is integer division) and then converts the result 1 to double (which is still 1, well, 1.0 to be precise). When you have (double) 3 / 2, then you tell the compiler to convert 3 to double first and then do 3.0 / 2, which is 1.5. :)

You can see for yourself that for example std::cout << (double (3) / 2) << endl; would result in 1.5, whereas std::cout << (double (3 / 2)) << endl; would result in 1.
Last edited on
I assumed that 3/2 would be automatically converted to the required type. So 3.0/2 would actually be 1.5. I'll watch out for that in the future! Thanks for the help. :)
never assume... know... ;)
Topic archived. No new replies allowed.