在C ++中两个整数的乘法 [英] Multiplication of two integers in 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)?
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和产品。然后产品投放到长期
,但太晚了,溢出已经触发。
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.
c $ c> a 或 b
long long
将被晋升。
Having one of a
or b
long long
should work as well, as the other would be promoted.
这篇关于在C ++中两个整数的乘法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!