3 * 1000000000作为int溢出,但是变量long long.为什么? [英] 3 * 1000000000 overflows as an int, but the variable is long long. Why?
问题描述
我有一个简单的c ++应用,可以执行以下计算
I have a simple c++ app that performs the following calculations
long long calcOne = 3 * 100000000; // 3e8, essentially
long long calcTwo = 3 * 1000000000; // 3e9, essentially
long long calcThree = 3 * 10000000000; // 3e10, essentially
如果我写下每个计算的结果,则会得到以下输出:
If I write the result of each calculation I get the following output:
calcOne = 300000000
calcTwo = -1294967296
calcThree = 30000000000
那么第二个计算为什么会失败?据我所知,它在long long类型(calcThree较大...)的范围内.
So why does the second calculation fail? As far as I can tell it is within the limits of a long long type (calcThree was larger...).
我正在Windows 10上使用Visual Studio2015.预先致谢.
I am using Visual Studio 2015 on Windows 10. Thanks in advance.
推荐答案
默认情况下,整数常量为 int
s.
Integer constants are, by default int
s.
1000000000
这可以适合 int
.因此,此常量被解析为 int
.但是将其乘以3会溢出int.
That can fit into an int
. So, this constant gets parsed as an int
. But multiplying it by 3 overflows int.
10000000000
对于int而言太大,因此此常量为 long long
,因此所得乘法不会溢出.
This is too big to an int, so this constant is a long long
, so the resulting multiplication does not overflow.
解决方案:明确使用 long long
常量:
Solution: explicitly use long long
constants:
long long calcOne = 3 * 100000000LL; // 3e8, essentially
long long calcTwo = 3 * 1000000000LL; // 3e9, essentially
long long calcThree = 3 * 10000000000LL; // 3e10, essentially
这篇关于3 * 1000000000作为int溢出,但是变量long long.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!