2

当我尝试在 C++ 中使用 setprecision(2) 对数字进行舍入时,会重新返回像“0.093”这样的数字——三位,而不是小数点后两位!我不知道为什么会这样。我在下面包含了我非常基本的代码,以防我严重遗漏了一些要点。谢谢!

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    double tax = 0.06 ; //Tax Rate
    float cost ; //Cost of item
    float computed ; //Non-rounded tax

    cout << "Enter the cost of the item: " ;
    cin >> cost ;

    computed = tax*cost;

    cout << "Computed: $" << computed << endl;
    cout << "Charged: $" << setprecision(2) << computed << endl; //Computed tax rounded to 2 decimal places



    return 0;

}
4

3 回答 3

8

This is because std::setprecision doesn't set the digits after the decimal point but the significant (aka "meaningful") digits if you don't change the floating point format to use a fixed number of digits after the decimal point. To change the format, you have to put std::fixed (documentaion) into your output stream:

cout << "Charged: $" << fixed << setprecision(2) << computed << endl;
于 2013-01-22T22:44:51.703 回答
0

来自:http ://www.cplusplus.com/reference/iomanip/setprecision/

十进制精度决定了在插入操作中写入以表示浮点值的最大位数。如何解释这取决于 floatfield 格式标志是否设置为特定符号。
...

在默认的浮点表示法上,精度字段指定要显示的有意义数字的最大数量,包括小数点之前和之后的数字。

在您的情况下:0.093, 93- 两个有意义的数字。

于 2013-01-22T22:46:57.563 回答
0

cout << 固定 <<setprecision(6)<< a<<endl; //添加任何你想要四舍五入的地方

于 2021-04-08T19:29:13.453 回答