【问题标题】:setw not working properlysetw 无法正常工作
【发布时间】:2017-10-09 05:47:45
【问题描述】:

我正在编写一个贷款摊销程序,但是当我使用“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++;
    }

输出

【问题讨论】:

  • setw 为打印语句中除第一个之外的每个项目,因此第一个的大小取决于它需要多少个字符。只有后面的会被填充到 15 个字符。
  • 另外,“Current Balance”是15个字符,所以打印在“month”之后,没有空格。

标签: c++ c++11


【解决方案1】:

我建议几件事:

第一个:将宽度增加到比列名的最大宽度稍长的位置。在这种情况下,您有 15 个字符长的“当前余额”,因此如果您使用 15 作为字段宽度,则不会在该列周围留出间距。

第二个:使用std::setwstd::left 作为您的第一列,也可以隔开我们的那一列。 (std::left 将左对齐第一列)

3rd:将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

【讨论】:

  • 我认为std::left修饰符是默认修饰符,可以省略。
猜你喜欢
  • 2016-12-01
  • 1970-01-01
  • 2016-09-01
  • 2012-07-11
  • 2018-04-08
  • 2017-04-20
  • 2018-10-02
  • 2016-09-04
  • 2010-10-06
相关资源
最近更新 更多