为什么在此代码中隐式类型转换结果不正确? [英] Why does implicit type conversion results incorrectly in this code?
问题描述
#include <iostream>
int main()
{
int number=65536;
long long temp=number*number;
std::cout << temp << std::endl;
return 0;
}
65536 的平方显然超出了 int
的范围.现在,如果我将 temp
声明为 int
,我将理解为什么会失败.但是,即使它是 long long
,它的输出始终为 0
.我认为这在某种程度上与隐式类型转换有关,但是我不明白为什么结果为 0
.
Square of 65536
is obviously out of int
's range. Now, if I had declared temp
as an int
, I would understand why this fails. But even though it's long long
, the output is always 0
. I believe this is somewhat related to implicit type conversion but I can't understand why the result is 0
.
这是因为c ++根本不允许将 int
转换为 long
吗?如果是这样,那为什么为什么用较小的数字呢?
Is this because c++ simply doesn't allow converting int
to long
? If so, then why does this work with smaller numbers?
推荐答案
(请注意, int
的范围可以小至-32767到+32767.)
(Note that the range of an int
can be as small as -32767 to +32767.)
number * number
是用 int
算术计算的,因为两个参数的类型均为 int
.由于您的 int
溢出,您的程序的行为是 undefined .
number * number
is evaluated in int
arithmetic since both arguments are of type int
. The behaviour of your program is undefined due to your int
overflowing.
您想要将结果分配给 long long
的事实与此无关.
The fact that you want to assign the result to a long long
is not relevant.
一种解决方案是编写 1LL *数字*数字
,以强制将参数提升为 long long
类型.
One solution would be to write 1LL * number * number
to force promotion of the arguments to long long
types.
这篇关于为什么在此代码中隐式类型转换结果不正确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!