【发布时间】:2012-12-05 09:02:05
【问题描述】:
我刚刚解决了我在 iOS 应用程序中遇到的一个相当奇怪的问题。我需要对传递给方法的值应用一个比例因子(我计算为64/38 ~= 1.684)。
我的问题的症结是这样的:
- (void)applyScaleTo:(int)value {
// value := 64
int first = value * (64/38)
NSLog(@"First: %d", first);
int second = (64 * value)/38;
NSLog(@"Second: %d", second);
}
所需值为107,但日志如下所示:
First: 64
Second: 107
我的解决方案是使用第二种方法,这很好,但我的问题是,为什么会出现这种差异? (顺便说一句,如果将first 更改为float,它仍然会记录为64.00000...。)
【问题讨论】:
-
64/38,因为操作数是整数,所以是 1 - 将结果更改为浮点数不会改变计算。
标签: objective-c c math floating-point