0

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

1 回答 1

1

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

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

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

stringstream ss;
ss << fixed << setprecision(2) << "$" << cost;
cout << left << "Cost:" << setw(COLFMT) << right << ss.str() << endl;
于 2019-10-25T06:13:41.400 回答