【发布时间】: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 没有与上面的其他数字对齐。