setw无法正常工作

时间:2017-10-08 20:53:45

标签: c++ c++11

我正在编写贷款摊还方案,但是当我使用“setw”设置我的列时,将“月份”和“当前余额”放在一起,而不是像我想要的那样间隔其他人。

我在终端的输出中包含了一张图片。

cout << "Month" // sets up columns
     << setw(15) << "Current Balance"
     << setw(15) << "Interest"
     << setw(15) << "Payment"
     << setw(15) << "New Balance \n" << endl;


int month_count = 1;
while( month_count <= number_of_months) // Loops while calculating the monthly interest and new balances produced after payments.
    {
    cout << month_count
         << setw(15) << loan_amount;

    double interest = loan_amount * monthly_rate;

    cout << setw(15) << interest
         << setw(15) << payment;

    loan_amount = loan_amount + interest - payment;

    cout << setw(15) << loan_amount << endl;

    month_count++;
    }

输出

Here is how its aligning

1 个答案:

答案 0 :(得分:0)

我建议一些事情:

1st:将宽度增加到略长于列名称最大宽度的值。在这种情况下,你有&#34;当前余额&#34;长度为15个字符,因此如果您使用15作为字段宽度,则不会在该列周围获得间距。

第二:将std::setwstd::left一起用于第一列,也可以将我们的列放在一起。 (std::left将左对齐第一列)

第3步:将std::setwstd::right一起使用,使您的值列右对齐值,并使用std::fixedstd::setprecision(2)的组合始终打印2个小数位为您的美元/分金额,这使它更容易阅读

以下是一个例子:

#include <iostream>
#include <iomanip>

using namespace std;

int number_of_months = 3;
double loan_amount = 50;
double monthly_rate = 2.3;
double payment = 10;

int main()
{
    cout << setw(7)  << std::left << "Month" // sets up columns
         << setw(17) << std::right << "Current Balance"
         << setw(17) << std::right << "Interest"
         << setw(17) << std::right << "Payment"
         << setw(17) << std::right << "New Balance" << '\n' << endl;


    int month_count = 1;
    while( month_count <= number_of_months) // Loops while calculating the monthly interest and new balances produced after payments.
    {
        cout << setw(7) << std::left << month_count
             << setw(17) << std::right << std::setprecision(2) << std::fixed << loan_amount;

        double interest = loan_amount * monthly_rate;

        cout << setw(17) << std::right << std::setprecision(2) << std::fixed << interest
             << setw(17) << std::right << std::setprecision(2) << std::fixed << payment;

        loan_amount = loan_amount + interest - payment;

        cout << setw(17) << std::right << std::setprecision(2) << std::fixed << loan_amount << endl;

        month_count++;
    }

    return 0;
}

<强>输出:

Month    Current Balance         Interest          Payment      New Balance

1                  50.00           115.00            10.00           155.00
2                 155.00           356.50            10.00           501.50
3                 501.50          1153.45            10.00          1644.95