0

我仍然是编码的初学者,但我对 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
4

0 回答 0