gpt4 book ai didi

c++ - 格式化表格看起来不错

转载 作者:行者123 更新时间:2023-11-27 23:46:17 28 4
gpt4 key购买 nike

我有以下代码

#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

我尝试过使用 left、setw,但似乎无法让它看起来正确。

我怎样才能实现这个例子?

最佳答案

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;

关于c++ - 格式化表格看起来不错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50334606/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com