在c++中使用setw和setprecision时,如何显示带值的$符号
How can I display a $ sign with a value while using setw and setprecision in c++
我想在第二列中的值旁边显示美元符号,但如果我将值转换为字符串,则setprecision不起作用,它显示的小数比我希望的要多。目前格式看起来不太好。
我当前的代码:
string unit = "m";
double width = 30.123;
double length = 40.123;
double perimeter = 2 * width + 2 * length;
double area = width * length;
double rate = (area <= 3000) ? 0.03 : 0.02;
double cost = area * rate;
const int COLFMT = 20;
cout << fixed << setprecision(2);
cout << setw(COLFMT) << left << "Length:"
<< setw(COLFMT) << right << length << " " << unit << endl;
cout << setw(COLFMT) << left << "Width:"
<< setw(COLFMT) << right << width << " " << unit << endl;
cout << setw(COLFMT) << left << "Area:"
<< setw(COLFMT) << right << area << " square" << unit << endl;
cout << setw(COLFMT) << left << "Perimeter:"
<< setw(COLFMT) << right << perimeter << " " << unit << endl;
cout << setw(COLFMT) << left << "Rate:"
<< setw(COLFMT) << right << rate << "/sqaure" << unit << endl;
cout << setw(COLFMT) << left << "Cost:"
<< setw(COLFMT) << right << "$" << cost << endl;
产生这种格式错误的输出:
Length: 40.12 m
Width: 30.12 m
Area: 1208.63 square m
Perimeter: 140.49 m
Rate: 0.03/square m
Cost: $36.26
"当前格式看起来不太好。">
这是因为std::right
与它后面的内容有关,在您的案例中是"$"。因此,美元符号是正确对齐的,而不是随后的价值。
你想要的是完全格式化的货币价值"36.26美元"正确对齐。因此,首先使用stringstream
将其构建为字符串。
stringstream ss;
ss << fixed << setprecision(2) << "$" << cost;
cout << left << "Cost:" << setw(COLFMT) << right << ss.str() << endl;
相关文章:
- 与 string.size() 比较时 int 的符号性显示警告
- 引入参数化构造函数后显示 LNK 2019 未解析外部符号的代码错误
- 在c++中使用setw和setprecision时,如何显示带值的$符号
- 视觉工作室未显示符号表?
- Unicode Chars显示为十进制数字而不是符号,我该如何修复
- 将零附加到数字时,无符号数字会显示不同的结果
- OpenGL符号突出显示visual studio Mac代码中的错误
- 无法使用 fstream 从二进制文件中读取字符串,而是显示奇怪的符号
- 在 mfc 应用程序中显示数学符号
- 使用转储箱显示 DLL 的外部符号 (UNDEF)
- 字符串流问题,我认为我的代码看起来不错,但它显示奇怪的符号
- OSX "ld" : 如何显示未解析符号的损坏名称?如何获取地图文件?
- 为什么非unicode应用程序系统语言环境使Unicode字体具有错误显示的符号字符
- 如何将数组更改为字符串以在C 中显示符号
- 体系结构x86_64的未定义符号-头文件中的显示功能
- 如何在禁用的MFC CEdit控件中显示插入符号
- Qt - 在像素操作后显示无符号字符
- 字符* 数组出现"multiple definitions"错误,但无符号字符数组未显示错误
- Mac上的Qt显示符号未在架构x86_64中找到
- 在c++和护士中显示%符号