2013-05-17 153 views
8

我想在格式化文本中做一些简单的输出。 Setprecision不会将我的变量输出到小数点后两位。C++ setprecision(2)打印一位小数?

例如,如果firstItemPrice = 2.20,输出为2.2,而不是2.20

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

int main() 
{ 

    string firstitem = ""; 
    string seconditem = ""; 
    double firstItemNum;  
    double firstItemPrice = 0.00; 
    double secondItemNum; 
    double secondItemPrice = 0.00; 

    //first item 
    cout << "Enter the name of Item 1: "; 
    getline(cin, firstitem); 
    cout << "Enter the number of " << firstitem << "s and the price of each: "; 
    cin >> firstItemNum >> firstItemPrice; 
    cin.ignore(); 

    //second item 
    cout << "Enter the name of Item 2: "; 
    getline(cin, seconditem); 
    cout << "Enter the number of " << seconditem << "s and the price of each: "; 
    cin >> secondItemNum >> secondItemPrice; 


    cout << left << setw(20) << "Item" << setw(10) << "Count" 
    << setw(10) << "Price" << left << "\n"; 

    cout << setw(20) << "====" << setw(10) << "====" << setw(10) 
    << "====" << left << "\n"; 

    cout << setw(20) << firstitem << setw(10) 
    << firstItemNum << setw(10) << setprecision(2) 
    << firstItemPrice << "\n"; 

    cout << setw(20) << seconditem << setw(10) << secondItemNum 
    << setprecision(2) << secondItemPrice << left << "\n"; 


    return 0; 
} 
+0

你的代码没问题。我编译它。它工作正常。它打印两位小数。你可能想尝试一个不同的编译器。 – 2014-03-12 02:12:09

回答

11

你在那里需要一个fixed做到这一点。

cout << fixed; 

设置回用:

cout.unsetf(ios_base::floatfield); 

在你的情况下,改变你的程序的最后有点像这个例子应该这样做:

cout << setw(20) << firstitem << setw(10) 
<< firstItemNum << setw(10) << fixed << setprecision(2) 
<< firstItemPrice << "\n"; 

cout.unsetf(ios_base::floatfield); 

cout << setw(20) << seconditem << setw(10) << secondItemNum 
<< fixed << setprecision(2) << secondItemPrice << left << "\n"; 

编辑旁白:不要使用浮点数来表示货币值。

+0

找出为什么浮动坏金融计算检查:http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency和http:// en。 wikipedia.org/wiki/Arbitrary-precision_arithmetic#Libraries – fduff

+0

对于不使用浮点的社论。 – hochl

2

http://www.cplusplus.com/reference/ios/ios_base/precision/

浮点精度决定于插入操作将要写入的位的最大数目来表示浮点值。如何解释这取决于floatfield格式标志是否设置为特定的记号(固定或科学)或未设置(使用默认记号,这不一定等同于固定或科学)。

默认语言环境: 使用默认浮点表示法中,精密字段指定在这两个前和那些小数点后总计数显示的有意义的最大位数。请注意,它不是最小值,因此如果数字可以用小于精度的数字显示,它不会将显示的数字填满尾随零。 在固定和科学符号中,精度字段都指定在小数点后显示多少个数字,即使这包括尾随的十进制零。在这种情况下,小数点前的数字与精度无关。