开发者

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 开发者_如何学JAVAis: 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?


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.


It casts number as a double so that float division is performed instead of integer division. Compare 1/2 versus 1.0/2.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜