我想在第二列中在它的值旁边显示美元符号,但是如果我将值转换成字符串,next精度就不起作用了,它显示的小数比我想要的要多。目前的格式看起来不太好。
我现在的代码是:
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发布于 2019-10-25 06:13:41
“目前的格式看起来不太好。
这是因为std::right与接下来的内容有关,在您的例子中是"$“。因此,美元信号是对齐的,而不是随后的价值。
你想要的是完全格式化的货币价值“36.26美元”是对齐的。因此,首先使用stringstream将其构建为字符串。
stringstream ss;
ss << fixed << setprecision(2) << "$" << cost;
cout << left << "Cost:" << setw(COLFMT) << right << ss.str() << endl;https://stackoverflow.com/questions/58552175
复制相似问题