gpt4 book ai didi

C++ 为什么会输出错误的复利?

转载 作者:行者123 更新时间:2023-11-28 05:46:53 24 4
gpt4 key购买 nike

一段时间以来,我一直在努力解决这个问题,我认为这与我用于计算的值有关。我对复利不是很熟悉,所以我不确定我是不是错了。任何帮助,将不胜感激。

#include <iostream>
#include <cmath>
using namespace std;

double interest_credit_card(double initial_balance, double interest_rate, int payment_months);
// Calculates interest on a credit card account according to initial balance,
//interest rate, and number of payment months.

int main ()
{
double initial_balance, interest_rate;
int payment_months;
char answer;

do
{

cout << "Enter your initial balace: \n";
cin >> initial_balance;
cout << "For how many months will you be making payments?\n";
cin >> payment_months;
cout << "What is your interest rate (as a percent)?: %\n";
cin >> interest_rate;
cout << endl;

cout << "You will be paying: $ " << interest_credit_card( initial_balance, interest_rate, payment_months) << endl;

cout << "Would you like to try again? (Y/N)\n";
cin >> answer;

}while (answer == 'Y' || answer == 'y');

cout << "Good-Bye.\n";

return 0;
}

double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
double compound_interest, compounding, compounding2, compounding3, compounding4;

while(payment_months > 0)
{
initial_balance = initial_balance + (initial_balance * interest_rate/100.0);
compounding = (interest_rate /12);
compounding2 = compounding + 1;
compounding3 = interest_rate * (payment_months/12);
compounding4 = pow(compounding2, compounding3);
compound_interest = initial_balance * compounding4;

initial_balance = initial_balance + compound_interest;

payment_months--;
}

return initial_balance;
}

输入和预期输出:

Enter your initial balance: 1000
For how many months will you be making payments?: 7
What is your interest rate (as a percent)?: 9
You will be paying: $1053.70

最佳答案

看起来你尝试了一堆东西然后把它们留在了里面。你尝试的第一个解决方案几乎是正确的,你只是忘记了“/12”:

double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
while (payment_months > 0)
{
initial_balance = initial_balance + (initial_balance * interest_rate / 100.0/12);

payment_months--;
}

return initial_balance;
}

有一点更好的风格:

double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
double total_payment = initial_balance;
double monthly_rate = interest_rate / 100.0 / 12;
for (int month = 1; month <= payment_months; ++month)
total_payment += total_payment * monthly_rate;

return total_payment;
}

关于C++ 为什么会输出错误的复利?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36052162/

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