【问题标题】:How to display a fixed number of digits in C++ without rounding如何在不四舍五入的情况下在 C++ 中显示固定位数
【发布时间】:2013-11-14 13:32:56
【问题描述】:

我有这个代码(非常基本):

#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。我知道我的代码会四舍五入最后一个十进制数,但这不是我想要的。

我怎样才能让它保持在 0.64 而不是 0.65 的位置?

【问题讨论】:

  • 您应该检查cin &gt;&gt; a 是否返回true。否则输入失败。

标签: c++ output decimal-point


【解决方案1】:

如果要将值截断到小数点后两位,可以将其乘以 100,截断为整数,然后除以 100,如下所示:

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

Demo on ideone.

【讨论】:

  • 哪个库有 trunc 因为我在 vs 2012 中有 cmath 并且它没有接受它
  • @user2529011 是&lt;cmath&gt;(参见演示,我为其添加了#include)。
  • 我做了,但还是不接受
  • error C3861: 'trunc': identifier not found I'm using VS2012 BTW
  • @user2529011 啊,我明白了,std::trunc 是在 C++11 中添加的,VS 2012 不是 C++11。您需要将其替换为floor(已编辑并更改了演示)。
【解决方案2】:

您可以使用trunc 截断到一定位数:

c = a / b;

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

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

对于通用函数:

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

然后使用

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

【讨论】:

  • 哪个库有 trunc 因为我在 vs 2012 中有 cmath 并且它没有接受它
  • 或者你可以不使用trunc方法将double转换成int
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多