9

書式設定されたテキストで簡単な出力を実行しようとしています。Setprecision で変数が小数点以下 2 桁まで出力されません。

たとえば、firstItemPrice = 2.20 の場合、出力は 2.20 ではなく 2.2 になります。

#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;
}
4

2 に答える 2

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";

編集上の余談: 通貨の値を表すために浮動小数点数を使用しないでください。

于 2013-05-17T22:45:17.623 に答える