10

下面有两种情况,操作看似相同,但产生的结果相差1。我想我不需要解释编程,很简单。

变量声明是第一个,场景1是1)和2 = 2),得到的结果列在每个场景的最后。

任何帮助将不胜感激。

int intWorkingNumber = 176555;

int intHundreds = 1;

int intPower = 1;

1)

int intDeductionValue = (intHundreds * 100 * pow(1000, intPower));

intWorkingNumber -= intDeductionValue;  

intWorkingNumber = 76555

2)

intWorkingNumber -= (intHundreds * 100 * pow(1000, intPower))

intWorkingNumber = 76554
4

1 回答 1

17

两个代码示例之间的区别在于转换为 int 的时间。

第一个版本与此代码类似,在减去之前将其转换为整数:

intWorkingNumber = 176555 - (int)(1 * 100 * pow(1000, 1));

第二个版本与此类似,在减去后转换为整数:

intWorkingNumber = (int)(176555 - (1 * 100 * pow(1000, 1)));

The function pow returns a floating point number. If the result of 1 * 100 * pow(1000, 1) is not exactly equal to 100000.0000 (and with floating point operations, you should not normally rely on exact results) these two are not equivalent.

Consider this simpler example:

x = 10 - (int)0.001;   // x = 10 - 0;     => x = 10
y = (int)(10 - 0.001); // y = (int)9.999; => y = 9
于 2012-08-12T10:12:12.437 回答