Reputation: 11
Can I know what is the reason for the output of t_temp
is 1.47123e+9
rather than 3.1536e+10
(t
)?
The codes of program is:
#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;
}
Upvotes: 0
Views: 126
Reputation: 179930
In a sense, YES, this is caused by #define
.
The following 2 changes also fixes the problem (pick one)
const long long asd = 86400;
const double asd = 86400;
Upvotes: 0
Reputation: 1374
When you calculate expression with integer values it casts to int32_t type, and the result is more than 2^32. You need to cast at least one of the operand to higher type.
#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;
}
Upvotes: 1