我还是编码的初学者,但我对setw()的工作原理感到困惑。我试图调整我的输出,但我无法这样做。我看过cplusplus网站,但显然我还是想不通。
也许某人可以提供示例或查看我的实际代码和输出?
/*A retail company must file a monthly sales tax report listing the sales for the month and the amount of
sales tax collected. Write a program that asks for the month, the year, and the total amount collected
at the cash register (that is, sales plus sales tax). Assume the state sales tax is 4 percent and the county
sales tax is 2 percent.*/
#include <iostream>
#include <iomanip>
using namespace std;
double calcStateTax(double inp) {
inp *= 0.04;
return inp;
}
double calcCountyTax(double inp){
inp *= 0.02;
return inp;
}
double calcSales(double inp){
inp = inp - (calcStateTax(inp) + calcCountyTax(inp));
return inp;
}
void outPut(string month, int year, double tot){
cout << "Month: " << month << " " << year << endl;
cout << "--------------------------\n";
cout << "Total Collected: $" << fixed << setprecision(2) << setw(20) << tot << endl;
cout << "Sales: $" << setw(20) << fixed << setprecision(2) << setw(20) << calcSales(tot) << endl;
cout << "County Sales Tax: $" << setw(20) << fixed << setprecision(2) << setw(20) << calcCountyTax(tot) << endl;
cout << "State Sales Tax: $" << setw(20) << fixed << setprecision(2) << setw(20) << calcStateTax(tot) << endl;
cout << "Total Sales Tax: $" << setw(20) << fixed << setprecision(2) << setw(20) << (calcStateTax(tot)+calcCountyTax(tot)) << endl;
}
int main() {
string month;
int year;
double totAmount;
cout << "Please enter the month: ";
cin >> month;
cout << "\nPlease enter the year: ";
cin >> year;
cout << "\nPlease enter total money collected including tax money: ";
cin >> totAmount;
cout << endl;
outPut(month, year, totAmount);
return 0;
}
输出:
Please enter the month: June
Please enter the year: 2010
Please enter total money collected including tax money: 15000
Month: June 2010
--------------------------
Total Collected: $ 15000.00
Sales: $ 14100.00
County Sales Tax: $ 300.00
State Sales Tax: $ 600.00
Total Sales Tax: $ 900.00
Program ended with exit code: 0
正如您所看到的......数字无法正确对齐。我如何使用它setw()?或者是否有更好的功能可用于我想要做的事情?
Please enter the year: 2010
Please enter total money collected including tax money: 15000
Month: june 2010
--------------------------
Total Collected: $ 15000.00
Sales: $ 14100.00
County Sales Tax: $ 300.00
State Sales Tax: $ 600.00
Total Sales Tax: $ 900.00