我正在尝试在格式化文本中做一些简单的输出.Setprecision不会将我的变量打印到两个小数位.
例如,如果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;
}
Run Code Online (Sandbox Code Playgroud)
Car*_*rum 11
你需要fixed在那里做到这一点.
cout << fixed;
Run Code Online (Sandbox Code Playgroud)
使用以下命令设置:
cout.unsetf(ios_base::floatfield);
Run Code Online (Sandbox Code Playgroud)
在您的情况下,更改程序的最后一位(如此示例)应该这样做:
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";
Run Code Online (Sandbox Code Playgroud)
编辑旁边:不要使用浮点数来表示货币值.
来自http://www.cplusplus.com/reference/ios/ios_base/precision/
浮点精度决定了在插入操作中写入以表达浮点值的最大位数。如何解释这取决于 floatfield 格式标志是设置为特定符号(固定或科学)还是未设置(使用默认符号,这不一定等同于固定或科学)。
对于默认语言环境: 使用默认浮点表示法,精度字段指定要显示的有意义数字的最大数量,包括小数点之前和之后的数字。请注意,它不是最小值,因此如果数字可以显示的位数少于精度,则它不会用尾随零填充显示的数字。在固定记数法和科学记数法中,精度字段准确指定小数点后显示的位数,即使这包括尾随小数零。在这种情况下,小数点前的数字与精度无关。
| 归档时间: |
|
| 查看次数: |
31342 次 |
| 最近记录: |