为什么一个简单的C++程序会有错误的结果?是 #define 引起的吗?
Why there is wrong result for a simple C++ program? Is it caused by #define?
我能知道输出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;
相关文章:
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 我的代码中有错误,未声明的标识符
- C++ LeetCode #377 的 DP 解决方案中,此代码是否有错误?
- 分配给浮点数的积分文字除法 - 为什么结果是错误的?
- 试图建立银行管理系统,但有错误
- 我试图创建临时对象的方式有错误吗
- 我的随机生成器是否不工作,或者我决定人/骨架是否击中对手的方式是否有错误
- 我在OpenCV中有错误的"approxPolyDP(ROI_Vertices, ROI_Poly, 1.0, true)"
- 我在这个 C++ 代码上有错误吗?
- 是视觉C++优化器错误还是我的代码中有错误?
- 为什么双算的结果是错误的?
- 为什么一个简单的C++程序会有错误的结果?是 #define 引起的吗?
- 对此有错误
- C :数据文件有错误:预期的无限制ID
- 一个带有参数的程序,为什么此程序有错误的答案
- 仅使用boost.datetime在Windows上有错误
- 使用向量循环时,是否有错误
- Microsoft Visual Studio发现我所有的CUDA设备端函数都有错误
- ArtoolKit校准结果节省错误
- 继承默认构造函数在 gcc 中失败并在 clang 中工作,哪个有错误?