为什么 int 到 long long int 的隐式转换在 C++ 中给出了意想不到的答案? [英] Why does implicit conversion of int to long long int give unexpected answer in C++?
问题描述
我读到从 int
到 long long int
的转换是促销,因此认为应该没有任何问题,因为没有数据丢失,不像反之亦然转换.
I read that conversion from int
to long long int
is promotion and hence thought that there shouldn't be any issue as there is no loss of data, unlike the vice versa conversion.
但是当我将两个大值的 int
相乘并将其存储在 long long int
中时,它显示的是负数.
But when I multiply two int
s of large value and store it in long long int
, it is showing me negative number.
例如:
int a=1000000, b=1000000;
long long int c=a*b;
cout<<c;
上面的代码给了我一个负值.有人能解释一下原因吗?
The above code gives me a negative value. Can someone explain why?
推荐答案
a*b
仍然是 int
类型.一旦它被评估,结果被然后转换为long long int
.到那时,要避免溢出已经太晚了.在执行乘法之前,将您的值之一转换为 long long int
.试试这个:
a*b
is still of type int
. Once it's evaluated, the result is then converted to long long int
. At that point it's too late to avoid overflow. Convert one of your values to long long int
before preforming the multiplication. Try this :
#include <iostream>
int main()
{
int a = 1000000, b = 1000000;
long long int c = static_cast<long long int>(a)*b;
std::cout << c;
return 0;
};
这篇关于为什么 int 到 long long int 的隐式转换在 C++ 中给出了意想不到的答案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!