3

I'm trying to divide one number by another and then immediately ceil() the result. These would normally be variables, but for simplicity let's stick with constants.

If I try any of the following, I get 3 when I want to get 4.

double num = ceil(25/8); // 3
float num = ceil(25/8); // 3
int num = ceil(25/8); // 3

I've read through a few threads on here (tried the nextafter() suggestion from this thread) as well as other sites and I don't understand what's going on. I've checked and my variables are the numbers I expect them to be and I've in fact tried the above, using constants, and am still getting unexpected results.

Thanks in advance for the help. I'm sure it's something simple that I'm missing but I'm at a loss at this point.

Community
  • 1
  • 1
seanjames
  • 51
  • 1
  • 4

2 Answers2

16

This is because you are doing integer arithmetic. The value is 3 before you are calling ceil, because 25 and 8 are both integers. 25/8 is calculated first using integer arithmetic, evaluating to 3.

Try:

double value = ceil(25.0/8);

This will ensure the compiler treats the constant 25.0 as a floating point number.

You can also use an explicit cast to achieve the same result:

double value = ceil(((double)25)/8);
driis
  • 161,458
  • 45
  • 265
  • 341
  • Thanks very much! so that leading (double) in your second suggestion casts or "forces" the value of 25 into a double before dividing by 8, thus allowing the result to be of type double? – seanjames Oct 16 '12 at 20:29
  • Yes, exactly. The former, using a decimal point, does the same, but does so by forcing the compiler to bake in the constant using the floating point type. – driis Oct 16 '12 at 20:32
4

This is because the expressions are evaluated before being passed as an argument to the ceil function. You need to cast one of them to a double first so the result will be a decimal that will be passed to ceil.

double num = ceil((double)25/8);
PherricOxide
  • 15,493
  • 3
  • 28
  • 41