Dan*_*nzo 2 c++ boolean-logic overflow boolean-expression
我有以下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;
}
Run Code Online (Sandbox Code Playgroud)
首先,我得到一个整数溢出的警告,这让我感到奇怪,因为数字467510400*1000000完全落在长long int的范围内,不是吗?其次,我得到以下输出:
1
0
3
0
Run Code Online (Sandbox Code Playgroud)
如果在两种情况下,currentDt-addedDt的计算结果为0,那么第三个if语句怎么可能计算为true?
467510400*1000000
在范围内long long
,但不在范围内int
.由于两个文字都是类型int
,产品的类型也是类型int
- 并且会溢出.仅仅因为您将结果分配给a long long
不会更改分配的值.出于同样的原因,在:
double d = 1 / 2;
Run Code Online (Sandbox Code Playgroud)
d
将坚持0.0
而不是0.5
.
您需要明确地将其中一个文字转换为更大的整数类型.例如:
long long int addedDt = 467510400LL * 1000000;
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
102 次 |
最近记录: |