本文介绍了如何在C ++中显示固定数量的数字而不四舍五入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有此代码(非常基本):
I have this code (very basic):
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float a = 0.0,
b = 0.0,
c = 0.0;
cout<<"Input a: ";
cin>>a;
cout<<"input b: ";
cin>>b;
cout<<endl;
c = a / b;
cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;
return 0;
}
当我输入两个数字(例如,a = 513和b = 791)时,我得到0.65.计算器显示正确的答案是0.648.我知道我的代码会将最后一个十进制数字四舍五入,但这不是我想要的.
When I enter two numbers (say, a = 513 and b = 791) I get 0.65. Calculator shows that the correct answer is 0.648. I understand that my code rounds up the last decimal number but this is not what I want.
我如何才能将其保持在0.64而不是0.65的水平?
How can I get it to where it just stays as 0.64 and not 0.65?
推荐答案
如果要将值截断为两位小数,可以将其乘以100,截断为整数,然后除以100,如下所示:
If you would like to truncate the value to two decimal places, you can multiply it by 100, truncate to integer, and then divide by 100, like this:
c = a / b;
c = floor(100 * c) / 100;
cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;
这篇关于如何在C ++中显示固定数量的数字而不四舍五入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!