我正在尝试创建一个有组织的图表,其中包含每个月每种食物的金额。我能够排在第一排,但在那之后,有些事情开始发生了。这就是我最终得到的:
这是我尝试使用 setw() 的代码,但我似乎无法在它输出第一个数组元素后更改它的数字。
void sales_report() {
for (int i = 0; i < 7; i++) {
cout << setw(17) << months[i] << " ";
}
cout << endl << foods[0] << " ";
for (int i = 0; i < 6; i++) {
sumapple += apples[i];
cout << setprecision(2) << fixed << setw(8) << money << apples[i] << " ";
}
cout << setprecision(2) << fixed << setw(8) << money << sumapple << endl;
cout << foods[1] << " ";
for (int i = 0; i < 6; i++) {
sumoranges += oranges[i];
cout << setprecision(2) << fixed << setw(7) << money << oranges[i] << " ";
}
cout << setprecision(2) << fixed << setw(7) << money << sumoranges << endl;
cout << foods[2] << " ";
for (int i = 0; i < 6; i++) {
sumpears += pears[i];
cout << setprecision(2) << fixed << setw(10) << money << pears[i] << " ";
}
cout << setprecision(2) << fixed << setw(10) << money << sumpears << endl;
cout << foods[3] << " ";
for (int i = 0; i < 6; i++) {
sumtomatoes += tomatoes[i];
cout << setprecision(2) << fixed << setw(7) << money << tomatoes[i] << " ";
}
cout << setprecision(2) << fixed << setw(7) << money << sumtomatoes << endl;
cout << foods[4] << " ";
for (int i = 0; i < 6; i++) {
sumcherries += cherries[i];
cout << setprecision(2) << fixed << setw(6) << money << cherries[i] << " ";
}
cout << setprecision(2) << fixed << setw(6) << money << sumcherries << endl << totalmonth;
for (int i = 0; i < 6; i++) {
total = apples[i] + oranges[i] + pears[i] + tomatoes[i] + cherries[i];
cout << setprecision(2) << fixed << setw(9) << money << total << " ";
}
}
最佳答案
您正在使用不同的 std::setw()每个 for
循环中的值。因此错位。使用相同的值。
关于c++ - 使用 setw() c++ 格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42102202/