格式化表看起来不错

时间:2018-05-14 16:02:34

标签: c++

我有以下代码

#include "string"
#include "iostream"
#include "cmath"
#include "iomanip"

std::string name, item_name;
double loan_amount, annual_interest_rate;
int number_of_years;

double rate;
int number_of_payments;
double monthly_payments, total_amount_paid, total_interest_paid;

int main() {
    std::cout << "Welcome to the Monthly Payment Program." << std::endl << std::endl;
    std::cout << "Enter your name: ";
    std::getline(std::cin, name);
    std::cout << "Item being financed: ";
    std::getline(std::cin, item_name);
    std::cout << "Enter the loan amount: ";
    std::cin >> loan_amount;
    std::cout << "Enter the annual interest rate (in percentage): ";
    std::cin >> annual_interest_rate;
    std::cout << "Enter the duration of the loan in years: ";
    std::cin >> number_of_years;

    rate = annual_interest_rate / (12 * 100);
    number_of_payments = number_of_years * 12;
    monthly_payments = (rate * std::pow((1 + rate), number_of_payments))/(std::pow((1 + rate), number_of_payments) - 1);
    total_amount_paid = number_of_payments * monthly_payments;
    total_interest_paid = total_amount_paid - loan_amount;

    std::cout << std::endl;

    int width = 30;
    std::cout << std::left << std::setw(width) << "Name: " << name << std::endl;
    std::cout << std::left << std::setw(width) << "Item being financed: "  << item_name << std::endl;
    std::cout << std::left << std::setw(width) << std::setprecision(3) << "Monthly Interest Rate: "  << rate << "%" << std::endl;
    std::cout << std::left << std::setw(width) << "Number of Payments: "   << number_of_payments << std::endl;
    std::cout << std::left << std::setw(width) << std::setprecision(2) << "Monthly Payment: "  << "$ " << monthly_payments << std::endl;
    std::cout << std::left << std::setw(width) << std::setprecision(2) << "Total Amount Paid: "  << "$ " <<total_amount_paid << std::endl;
    std::cout << std::left << std::setw(width) << std::setprecision(2) << "Interest Paid: " << "$ " <<total_interest_paid << std::endl;
}

当我运行代码时,它看起来像这样

欢迎使用月度付款计划。

Enter your name: John Doe
Item being financed: Bass
Enter the loan amount: 15000
Enter the annual interest rate (in percentage): 8
Enter the duration of the loan in years: 3

Name:                         John Doe
Item being financed:          Bass
Monthly Interest Rate:        0.00667%
Number of Payments:           36
Monthly Payment:              $ 0.031
Total Amount Paid:            $ 1.1
Interest Paid:                $ -1.5e+04

我不在乎计算是错误的,但是,我需要它看起来像这样

layout expected

我尝试过玩左,setw,似乎无法让它看起来正确。

我如何实现这个例子?

1 个答案:

答案 0 :(得分:3)

Iomanip功能不是永久性的。需要在每次输出之前调用它们。

示例:

std::cout << std::left << std::setw( width ) 
          << "Interest Paid: "
          << "$ " 
          << std::right << std::fixed << std::setw( width ) << std::setprecision( 2 )  
          << total_interest_paid
          << std::endl;