[英]weird calculation result
why d
is not equal b
in this example? 为什么d
在这个例子中不等于b
?
unsigned int z = 176400;
long a = -4;
long b = a*z/1000; //b=4294261
long c = a*z; // c=-705600
long d = c/1000; // d =-705
I use Visual Studio 2008, windows XP, core2duo. 我使用Visual Studio 2008,Windows XP,core2duo。 Thanks. 谢谢。
It looks like you are using a platform where int
and long
have the same size. 看起来您正在使用int
和long
具有相同大小的平台。 (I've inferred this by the fact that if long
was able to hold all the valid values of unsigned int
you would not see the behaviour that you are seeing.) (我已经推断出这个事实,如果long
能够保存unsigned int
所有有效值,你将看不到你所看到的行为。)
This means that in the expression a*z
, both a
and z
are converted to unsigned long
and the result has type unsigned long
. 这意味着在表达式a*z
, a
和z
都转换为unsigned long
,结果的类型为unsigned long
。 (ISO/IEC 14882:2011, 5 [expr] / 9 ... "Otherwise, both operands shall be converted to the unsigned integer type corresponding to the type of the operand with signed integer type.") (ISO / IEC 14882:2011,5 [expr] / 9 ...“否则,两个操作数都应转换为无符号整数类型,对应于带有符号整数类型的操作数的类型。”)
c
is the result of converting this expression from unsigned long
to long
and in your case this results in an implementation defined result (that happens to be negative) as the positive value of a*z
is not representable in a signed long
. c
是从这个表达式转换的结果unsigned long
到long
和你的情况,这导致在一个实现中定义的结果(即恰好是负)作为正值a*z
的署名是不能表示long
。 In c/1000
, 1000
is converted to long
and long
division is performed (no pun intended) resulting in a long
(which happens to be negative) and is stored to d
. 在c/1000
, 1000
被转换为long
和long
除法(没有双关语)导致long
(恰好是负)并存储到d
。
In the expressions a*z/1000
, 1000
(an expression of type int
) is converted to unsigned long
and the division is performed between two unsigned long
resulting in a positive result. 在表达式a*z/1000
, 1000
(类型为int
的表达式)被转换为unsigned long
并且在两个unsigned long
之间执行除法,从而得到正结果。 This result is representable as a long
and the value is unchanged on converting to long
and storing to b
. 此结果可表示为long
并且在转换为long
并存储到b
时值不变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.