问题
I have a number (let's say, 34), and I want to find its next multiple of ten. I can do this by:
- Dividing the number by 10
- Rounding it up to a whole number
- 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).
- Using integer arithmetic, number/10 is number/10 rounded down, ie 3.
- ceil(3) = 3
- 3*10 = 30
If you have the cast, the following happens:
- (double)number = 34.0
- 34.0 / 10 = 3.4
- ceil(3.4) = 4.0
- 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