简体   繁体   English

如何在没有舍入的情况下在C ++中显示固定数量的数字

[英]How to display a fixed number of digits in C++ without rounding

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;
}

When I enter two numbers (say, a = 513 and b = 791) I get 0.65. 当我输入两个数字(例如,a = 513和b = 791)时,我得到0.65。 Calculator shows that the correct answer is 0.648. 计算器显示正确的答案是0.648。 I understand that my code rounds up the last decimal number but this is not what I want. 我明白我的代码会将最后一个十进制数字舍入,但这不是我想要的。

How can I get it to where it just stays as 0.64 and not 0.65? 如何将它保持在0.64而不是0.65的位置?

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: 如果要将值截断为两位小数,可以将其乘以100,截断为整数,然后除以100,如下所示:

c = a / b;
c = floor(100 * c) / 100;
cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;

Demo on ideone. 在ideone上演示。

You can use trunc to truncate to a certain number of digits: 您可以使用trunc截断为一定数量的数字:

c = a / b;

// truncate past two decimals:
c = trunc(c * 100) / 100;

cout<<"Result: "<<fixed<<setprecision(2)<<c<<endl;

of for a generic function: 对于通用函数:

int trunc(double val, int digits)
{
    double pow10 = pow(10,digits);
    return trunc(val * pow10) / pow10;
}

then use 然后用

cout << "Result: " << fixed << setprecision(2) << trunc(c,2) << endl;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM