0

我正在为我的编程课编写这段代码,我得到了其他一切工作,但是我的输出格式不适合我。

#include <iostream>
#include <iomanip>
#include <ios>

    using namespace std;

    int main()
    {
        double tip_fifteen;
        double tip_twenty;
        double tax;
        double bill;
        char dollars = '$';
        float meal_cost;

        cout << "Enter the meal cost: ";
        cin >> meal_cost;
        tip_twenty = meal_cost * .20;
        tip_fifteen = meal_cost * .15;
        tax = meal_cost * 0.0975;
        cout << "******************************************" << endl;

        //beginning outputs
        int digits;
        digits = meal_cost * 100 / 100;
        cout << setw(10) << left << "Meal Cost " << dollars;
        cout << setw(to_string(digits).length() + 3) << fixed << showpoint << setprecision(2) << meal_cost << endl;

        cout << setw(10) << left << "Tax " << dollars;
        cout << setw(to_string(digits).length() + 3) << fixed << showpoint << setprecision(2) << tax << endl;

        cout << setw(10) << left << "Tip (15%) " << dollars;
        cout << setw(to_string(digits).length() + 3) << fixed << showpoint << setprecision(2) << tip_fifteen << endl;

        //tip outputs then final output statements
        cout << setw(10) << left << fixed << setprecision(2) << "Tip (20%) " << dollars << tip_twenty << endl;
        bill = tip_fifteen + meal_cost + tax;
        cout << "Your total bill is " << fixed << setprecision(2) << dollars << bill << " after 15% gratuity." << endl << "or" << endl;
        bill = tip_twenty + meal_cost + tax;
        cout << "Your total bill is " << fixed << setprecision(2) << dollars << bill << " after 20% gratuity." << endl;



return 0;

我希望我的输出看起来像这样

Enter the meal cost: 56
******************************************
Meal Cost $ 56.00
Tax       $  5.46
Tip (15%) $  8.40
Tip (20%) $ 11.20
Your total bill is 69.86 after 15% gratuity.
or
Your total bill is 72.66 after 20% gratuity.

我的输出看起来像这样

Enter the meal cost: 56
******************************************
Meal Cost $56.00
Tax       $5.46 
Tip (15%) $8.40 
Tip (20%) $11.20
Your total bill is $69.86 after 15% gratuity.
or
Your total bill is $72.66 after 20% gratuity.

我在使用带有浮点数的 setw 时遇到问题,但是当我尝试将相同的变量设置为 int 时它不起作用。我也尝试过使用 setw(25) 看看它是否会以某种方式起作用,不幸的是它没有

4

2 回答 2

1

right如果你想让它们向右对齐,你需要使用,你还需要在后面添加一个空格“”dollars

cout << setw(10) << left << "Meal Cost " << dollars << " ";
cout << setw(to_string(digits).length() + 3) << fixed << right << showpoint << setprecision(2) << meal_cost << endl;

对于所有打印的报表,您将获得:

******************************************
Meal Cost $ 56.00
Tax       $  5.46
Tip (15%) $  8.40
Tip (20%) $ 11.20
于 2019-02-20T00:11:50.760 回答
0

为了在价格列中有填充,setw必须设置为足够大的宽度。

例如:

std::cout << "$" << std::setw(10) << std::fixed
          << std::setprecision(2) << 56.0f << std::endl;

印刷:

$     56.00

您的代码将宽度设置为:

std::to_string(digits).length() + 3

这只有 5 个字符,刚好适合“56.00”。对于左侧的额外填充,您应该增加setw宽度。

于 2019-02-19T23:39:19.563 回答