【发布时间】:2015-10-27 19:59:08
【问题描述】:
我有以下 c++ 代码:
#include <iostream>
using namespace std;
int main()
{
long long int currentDt = 467510400*1000000;
long long int addedDt = 467510400*1000000;
if(currentDt-addedDt >= 0 && currentDt-addedDt <= 30*24*3600*1000000)
{
cout << "1" << endl;
cout << currentDt-addedDt << endl;
}
if(currentDt-addedDt > 30*24*3600*1000000 && currentDt-addedDt <= 60*24*3600*1000000)
{
cout << "2" << endl;
cout << currentDt-addedDt << endl;
}
if(currentDt-addedDt > 60*24*3600*1000000 && currentDt-addedDt <= 90*24*3600*1000000)
{
cout << "3" << endl;
cout << currentDt-addedDt << endl;
}
return 0;
}
首先,我收到一个整数溢出警告,这让我觉得很奇怪,因为数字 467510400*1000000 正好落在 long long int 的范围内,不是吗?其次,我得到以下输出:
1
0
3
0
如果在这两种情况下 currentDt-addedDt 的计算结果都为 0,那么第三个 if 语句怎么可能计算结果为 true?
【问题讨论】:
-
如果你使用
467510400ll * 1000000ll等会发生什么?也许编译器将它们相乘为ints。 -
long long int,是的,但是所有这些常数的数学运算很可能以int
标签: c++ overflow boolean-logic boolean-expression