为什么长久n = 2000 * 2000 * 2000 * 2000;溢出? [英] Why does long long n = 2000*2000*2000*2000; overflow?
问题描述
long long int n = 2000*2000*2000*2000; // overflow
long long int n = pow(2000,4); // works
long long int n = 16000000000000; // works
为什么第一个溢出(将整数文字常量与要分配给long long的整数相乘)?
Why does the first one overflow (multiplying integer literal constants to assign to a long long)?
它与第二个或第三个有什么不同?
What's different about it vs. the second or third ones?
推荐答案
因为 2000
是 int
,通常为32位.只需使用 2000LL
.
Because 2000
is an int
which is usually 32-bit. Just use 2000LL
.
@AdrianMole在其中建议使用后缀"LL"代替后缀"LL",现在将其删除.请检查他的答案.
默认情况下,整数文字是可以保留其值但不小于 int
的最小类型. 2000
可以很容易地存储在int中,因为该标准保证它实际上至少是16位类型.
By default, integer literals are of the smallest type that can hold their value but not smaller than int
. 2000
can easily be stored in an int since the Standard guarantees it is effectively at least a 16-bit type.
总是以存在的较大类型但不小于 int
的类型调用算术运算符:
Arithmetic operators are always called with the larger of the types present but not smaller than int
:
-
char * char
将被提升为operator *(int,int)-> int
-
char * int
调用operator *(int,int)-> int
-
long * int
调用operator *(long,long)-> long
-
int * int
仍会调用operator *(int,int)-> int
.
char*char
will be promoted tooperator*(int,int)->int
char*int
callsoperator*(int,int)->int
long*int
callsoperator*(long,long)->long
int*int
still callsoperator*(int,int)->int
.
类型不取决于结果是否可以以推断的类型存储.这正是您遇到的问题-乘法是用 int
s完成的,但是结果溢出,因为它仍然存储为 int
.
The type is not dependent on whether the result can be stored in the inferred type. Which is exactly the problem happening in your case - multiplication is done with int
s but the result overflows as it is still stored as int
.
C ++不像Haskell那样支持基于目的地的推断类型,因此分配是无关紧要的.
C++ does not support inferring types based on their destination like Haskell can so the assignment is irrelevant.
这篇关于为什么长久n = 2000 * 2000 * 2000 * 2000;溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!