Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "double" do in ceil(double)?

I have a number (let's say, 34), and I want to find its next multiple of ten. I can do this by:

  1. Dividing the number by 10
  2. Rounding it up to a whole number
  3. Multiplying by 10.

After a bit of research, I discovered that this is the code for that in Objective C:

int number = 34;
int roundedNumber = ceil((double)number/10)*10;

My question is: what is the (double) for, and why does removing (double) cause it to round down instead of up?

I understand from googling that changes the float format to "double precision" but, to be honest, this is way too complicated for me. Can anyone provide a simple explanation of what it is doing?

like image 367
Ric Levy Avatar asked Jan 20 '23 18:01

Ric Levy


1 Answers

If you don't have the cast the following happens (if number is 34).

  1. Using integer arithmetic, number/10 is number/10 rounded down, ie 3.
  2. ceil(3) = 3
  3. 3*10 = 30

If you have the cast, the following happens:

  1. (double)number = 34.0
  2. 34.0 / 10 = 3.4
  3. ceil(3.4) = 4.0
  4. 4.0*10 = 40

The important thing to realise is Integer division always rounds towards 0.

like image 148
Nick Fortescue Avatar answered Jan 30 '23 13:01

Nick Fortescue