C ++ setprecision(2)打印一个小数点? [英] C++ setprecision(2) printing one decimal?

查看:190
本文介绍了C ++ setprecision(2)打印一个小数点?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Hey there :)我想在格式化文本中做一些简单的输出。不管什么原因,setprecision不是printig我的变量到两个小数位。感谢任何帮助。

Hey there :) I'm trying to do some simple output in formatted text. For whatever reason, setprecision is not printig my variables out to two decimal places. Thanks for any help.

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

for example if firstItemPrice = 2.20, the output is 2.2 instead of 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;
}


推荐答案

$ c>固定。

You need a fixed in there to do that.

cout << fixed;

使用以下命令重新设置:

Set it back using:

cout.unsetf(ios_base::floatfield);

在这种情况下,像这样改变程序的最后一位应该:

In your case, changing the last bit of your program like this example should do it:

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

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

Editorial aside: Don't use floating point numbers to represent currency values.

这篇关于C ++ setprecision(2)打印一个小数点?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆