What does the “double” do in ceil(double)?

白昼怎懂夜的黑 提交于 2019-12-23 12:49:23

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/5976832/what-does-the-double-do-in-ceildouble

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!