【问题标题】:How can I display a $ sign with a value while using setw and setprecision in c++在 c++ 中使用 setw 和 setprecision 时如何显示带有值的 $ 符号
【发布时间】:2020-02-21 10:21:40
【问题描述】:

我想在第二列的值旁边显示美元符号,但如果我将值转换为字符串,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

【问题讨论】:

  • 我想声明我曾尝试使用 floor() 进行舍入,但转换为字符串时显示 36.260000。我尝试了其他一些方法,但不幸的是,我似乎无法弄清楚如何显示 $36.26,宽度和长度分别为 30.123 和 40.123。
  • 上面显示的程序在我运行时已经打印了“Cost: $36.26”。问题出在哪里?
  • 问题是输出格式错误,$36.26 没有与上面的其他数字对齐。

标签: c++ string setw


【解决方案1】:

“目前的格式看起来不太好。”

那是因为std::right 与它后面的内容有关,在您的情况下为“$”。所以美元符号是右对齐的,而不是后面的值。

您想要的是右对齐的完全格式化的货币值“$36.26”。因此,首先使用stringstream 将其构建为字符串。

stringstream ss;
ss << fixed << setprecision(2) << "$" << cost;
cout << left << "Cost:" << setw(COLFMT) << right << ss.str() << endl;

【讨论】:

    猜你喜欢
    • 2021-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 2013-09-23
    相关资源
    最近更新 更多