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

末鹿安然 提交于 2019-12-19 17:46:09

问题


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. 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.

How can I get it to where it just stays as 0.64 and not 0.65?


回答1:


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;

Demo on ideone.




回答2:


You can use trunc to truncate to a certain number of digits:

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;


来源:https://stackoverflow.com/questions/19759131/how-to-display-a-fixed-number-of-digits-in-c-without-rounding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!