gpt4 book ai didi

C++,利息计算器不显示正确的输出

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:03 24 4
gpt4 key购买 nike

问题是“编写一个程序,读取初始投资余额和利率,然后打印投资达到 100 万美元所需的年数。”

  • 我输入的金额是 100,利率是 3。但是当我编译并运行时,输出是 29,这是不正确的,因为数量只有 187,根本不接近一百万。
/*
Question: Write a program that reads an initial
investment balance and an interest rate, then
prints the number of years it takes for the
investment to reach one million dollars.
*/

#include <iostream>

using namespace std;

int main()
{
//Obtain user amount
double amount;
cout << "Please enter an initial investment balance ($0.00): $";
cin >> amount;

//Obtain user interest rate
double interest_rate;
cout << "Please enter an interest rate: ";
cin >> interest_rate;

//Convert interest rate to decimal
interest_rate = interest_rate / 100;
int time = 1;

//Calculate how many years
while (amount < 1000000)
{
amount = amount * (1 + (interest_rate * time));
++time;
}

//Display years
cout << "Years to reach one million: " << time;
return 0;
}

我期望的输出是:

“达到一百万年:333300”

因为 333300 正好是一百万。

最佳答案

一年后,金额会增长到

amount * (1 + interest_rate)

两年后,数量增长到

amount * (1 + interest_rate) * (1 + interest_rate)

假设您的利率每年复利。您包含的 time 和连续乘以 amount 是错误的。

请注意,这里有一个封闭形式的解决方案。对于利率r,初始金额I,最终金额A,年数t

t = ln(A / I) / ln(1 + r)

您需要对其进行汇总。

关于C++,利息计算器不显示正确的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56292371/

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