为什么一个简单的C++程序会有错误的结果?是 #define 引起的吗?

Why there is wrong result for a simple C++ program? Is it caused by #define?

本文关键字:结果 有错误 #define 程序 一个 C++ 简单 为什么      更新时间:2023-10-16

我能知道输出t_temp 1.47123e+9而不是3.1536e+10(t(的原因是什么吗?

程序代码为:

#include<iostream>
using namespace std;
#define asd 86400    
int main()
{
    double t, t_temp;    
    t = 31536000000;
    t_temp = 365000 * asd;
    cout << t << endl;
    cout << t_temp << endl;    
    return 0;
}

当您使用整数值计算表达式时,它会强制转换为int32_t类型,结果大于 2^32。您需要将至少一个操作数强制转换为更高级别的类型。

#include<iostream>
#include<numeric>
using namespace std;
#define asd 86400
int main()
{
    cout << std::numeric_limits<int32_t>::max()<<endl;//2147483647
    int16_t Int16Res = 365000 * asd;//Int16Res    int16_t    11264
    int32_t Int32Res = 365000 * asd;//Int32Res    int32_t    1471228928
    int64_t Int64Res1 = 365000 * asd; //Int64Res1    int64_t    1471228928
    int64_t Int64Res2 = uint64_t(365000) * asd; //Int64Res2    int64_t    31536000000
    double t, t_temp;
    t = 31536000000;
    t_temp = 365000.0 * asd;//t_temp    double    31536001024
    cout << t_temp << endl;
    return 0;
}

从某种意义上说,是的,这是由#define引起的。

以下 2 个更改也解决了问题(选择一个(

const long long asd = 86400;
const double asd = 86400;