gpt4 book ai didi

c++ - 编写代码使年利率翻倍

转载 作者:太空宇宙 更新时间:2023-11-04 14:43:13 25 4
gpt4 key购买 nike

我正在尝试编写一个年利率代码,让您输入任何金额,它会告诉您大约需要多少年才能使您的资金至少翻一番。给定的利率为每年 5%。问题是,它无法正常工作,并且显示的数字高得离谱,比如 200 年左右。

#include <iostream>
using namespace std;

int main() {
int deposit;
int counter;

cout << "Deposit an amount NO LESS than 1000." << endl;
cin >> deposit;

for (deposit ;; deposit = 1.05 * deposit) {
counter = counter+1;

if (deposit >= 2 * deposit) {
cout << endl;
cout << "Your money will double in "<< counter <<" years." << endl;
break;
}
}
}

最佳答案

您可以不使用循环,而是直接计算使钱翻倍所需的时间。

钱的数量不感兴趣,所以你不需要存储钱的数量。只有返回率才是有趣的。

可以直接计算为log(2) / log(r)其中 r是返回率。例如log(2) / log(1.05)为您提供准确的时间,使初始金额翻倍,返回率为 5%。

包括标准<cmath>标题获取 std::log() .

#include <iostream>
#include <cmath>

int main() {
double yearsToDouble = std::log(2) / std::log(1.05);
std::cout << "Your money will double in "<< yearsToDouble << " years." << std::endl;
}

关于c++ - 编写代码使年利率翻倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52717327/

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