C++中两个整数的乘法
我有一个非常基本的问题,但我不确定我是否理解这个概念.假设我们有:
I have a pretty basic question, but I am not sure if I understand the concept or not. Suppose we have:
int a = 1000000;
int b = 1000000;
long long c = a * b;
当我运行它时,c
显示负值,所以我也将 a
和 b
更改为 long long
然后一切都很好.那么为什么我必须更改 a
和 b
,当它们的值在 int
范围内并且它们的产品分配给 c
(即long long
)?
When I run this, c
shows negative value, so I changed also a
and b
to long long
and then everything was fine. So why do I have to change a
and b
, when their values are in range of int
and their product is assigned to c
(which is long long
)?
我正在使用 C/C++
I am using C/C++
推荐答案
int
在乘法之前没有提升为long long
,它们仍然是int
s 和产品也是如此.然后将产品转换为 long long
,但为时已晚,溢出发生了.
The int
s are not promoted to long long
before multiplication, they remain int
s and the product as well. Then the product is cast to long long
, but too late, overflow has struck.
拥有 a
或 b
long long
中的一个应该也可以工作,因为另一个会被提升.
Having one of a
or b
long long
should work as well, as the other would be promoted.
相关文章