objective-c中的计算未返回正确的值

objective-c中的计算未返回正确的值,objective-c,ios,floor,ceil,Objective C,Ios,Floor,Ceil,请查看这段代码,更具体地说是hourStep计算 int h = [[timeArray objectAtIndex:0] intValue]; int m = [[timeArray objectAtIndex:1] intValue]; int s = [[timeArray objectAtIndex:2] intValue]; int mm = [[timeArray objectAtIndex:3] intValue]; NSLog([NSString stringWithForma

请查看这段代码,更具体地说是hourStep计算

int h = [[timeArray objectAtIndex:0] intValue];
int m = [[timeArray objectAtIndex:1] intValue];
int s = [[timeArray objectAtIndex:2] intValue];
int mm = [[timeArray objectAtIndex:3] intValue];

NSLog([NSString stringWithFormat:@"time h:%d, m:%d, s:%d, mm:%d", h, m, s, mm]);
//time h:13, m:7, s:55, mm:105

float hourStep1 = m / 60;
float hourStep2 = h + hourStep1;
float hourStep3 = hourStep2 / 24;
float hourStep4 = hourStep3 * 15;

int hour1 = ceil(hourStep4);

NSLog([NSString stringWithFormat:@"hourStep1: %f, hourStep2: %f, hourStep3: %f, hourStep4: %f result: %d", hourStep1, hourStep2, hourStep3, hourStep4, hour1]);
//hourStep1: 0.000000, hourStep2: 13.000000, hourStep3: 0.541667, hourStep4: 8.125000 result: 9

float hourStep5 = ((h + (m / 60)) / 24) * 15; 
NSLog([NSString stringWithFormat:@"hourStep5: %f", hourStep5]);

//hourStep5: 0.000000
我已经将计算分解为不同的步骤以得到正确的答案,但是有人能解释为什么hourStep5不能产生hourStep4产生的结果吗

float hourStep5 = ((h + (m / 60)) / 24) * 15; 
计算在
int
中执行,而不是在
float
中执行。请注意,在C中(以及因此在Objective-C中),
=
右侧的等式首先执行,而不考虑左侧的类型(在这种情况下,
float

使用


相反。

这是整数除法和浮点除法之间的区别

这一行:

float hourStep3 = hourStep2 / 24;
计算结果为
13.0f/24
,结果为
0.541667f
(浮点除法)

在组合计算中,您只处理整数(不转换为介于两者之间的浮点),因此

计算为
13/24
,等于
0
(整数除法)。换成

(h + (m / 60)) / 24.0f

您将得到与上面相同的结果。

整个小时计算步骤5将被视为整数

尝试将h和m都铸造到该行的浮动中:

float hourStep5 = (( (float) h + ( (float) m / 60)) / 24) * 15; 

这不会产生与上述计算相同的结果,因为原始海报也在那里使用了
m/60
(自愿或无意,我不知道)。要模拟第一次计算,请意外使用
(h+(m/60))/24.0
。谢谢Yuji和Ole。不会再犯那种错误了!
(h + (m / 60)) / 24.0f
float hourStep5 = (( (float) h + ( (float) m / 60)) / 24) * 15;