問題描述
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
.
使用 LL
后綴代替 ll
是@AdrianMole 在評論中建議的,現在已刪除.請查看他的答案.
Using LL
suffix instead of ll
was suggested by @AdrianMole in, now deleted, comment. Please check his answer.
默認情況下,整數文字是可以保存其值但不小于 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
.
Crucially, 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 does so the assignment is irrelevant.
這篇關于為什么long long n = 2000*2000*2000*2000;溢出?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!