[英]Why doesn't C++ return a double on division?
I am trying to divide two integers and want the exact answer in double. 我正在尝试将两个整数相除,并希望将确切的答案加倍。 My code works fine for small values:
我的代码适用于较小的值:
#include<iostream>
using namespace std;
int main()
{
int max = 100;
int min = 10;
int n = 8;
double gap = (max-min)/(double)(n-1);
cout<<gap<<endl;
}
This prints 12.8571 这打印12.8571
But when I run this: 但是当我运行这个:
#include<iostream>
using namespace std;
int main()
{
int max = 99404748;
int min = 925679;
int n = 240;
double gap = (max-min)/(double)(n-1);
cout<<gap<<endl;
}
It prints 412046 while the actual answer is 412046.3138 它打印412046,而实际答案是412046.3138
What is the reason for this behaviour? 这种行为的原因是什么? Also, how can I fix it?
另外,我该如何解决?
Everything with your double
value is fine. 拥有
double
价值的一切都很好。 The result you see is just a matter of how it's represented in the std::ostream
. 您看到的结果只是在
std::ostream
中如何表示的问题。
Use the fixed
and setprecision()
I/O manipulators , to change the behavior of the representation: 使用
fixed
和setprecision()
I / O机械手来更改表示的行为:
#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
int max = 99404748;
int min = 925679;
int n = 240;
double gap = (max-min)/(double)(n-1);
cout << fixed << setprecision(4) <<gap<<endl;
// ^^^^^ ^^^^^^^^^^^^^^^
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.