2013-01-22 123 views
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; 

} 
+0

根据http://www.cplusplus.com/reference/iomanip/setprecision,这需要2位数_precision_(2位有效数字),而不是小数点后的2位数。也许你应该看看http://www.cplusplus.com/reference/iomanip。 – vonbrand

回答

7

这是因为std::setprecision没有设置数字小数点后但显著(又名“有意义”)的数字,如果你不改变浮点格式使用固定小数点后的位数。要更改格式,你必须把std::fixed (documentaion)到您的输出流:

cout << "Charged: $" << fixed << setprecision(2) << computed << endl; 
0

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

小数精度决定的最大位数要在插入操作的书面表达浮点值。如何解释这取决于floatfield格式标志是否设置为特定的记号。
...

在默认的浮点数表示法上,精度字段指定了小数点之前和小数点之后显示的有效数字的最大总数。

在你的情况:0.09393 - 两个有意义的数字。