我用C++简单计算银行利率的方式制作了这个程序,作为家庭作业的一部分。答案是错误的,但我仍然不明白为什么,当我尝试更高的输入数字时,错误会变得更大......有关如何解决此问题的说明被注释为程序的第一行。
我尝试将所涉及的变量从浮点数切换到双精度,然后切换到长双精度,它仍然是相同的答案......
谁能弄清楚为什么?
// Homework 2 Task 1.cpp : Show bank balance after loan with user-input factors
//Try the code with 100 deposited sum, 5% interest and 3 months total time
//The answer will show 302.087 whereas the true answer should be 302.507
#include "stdafx.h"
#include <iostream>
using namespace std;
long double compoundVal(unsigned int, unsigned short int, unsigned short int);
void main()
{
unsigned int DepSum;
unsigned short int IntRate, NrMonths;
cout << "Please enther the amount you expect to deposit each month: ";
cin >> DepSum;
cout << "nThe amount of money that you will have in your account after 6 months with Inte-rest Rate of 5% will be: "<<compoundVal(DepSum, 5, 6); //Answering the first part of this task, where the user has to specify the Deposit Sum, and will receive the amount after 6 months with interest of 5%
cout << "nnYou can also see the account balance with interest rate and number of months of your choice.nPlease enter the Interest Rate of your choice: ";
cin >> IntRate;
cout << "nNow enter the number of months you intend to have the account: ";
cin >> NrMonths;
cout << "nThis will be your account balance: " << compoundVal(DepSum, IntRate, NrMonths) << endl;
}
long double compoundVal(unsigned int d, unsigned short int i, unsigned short int n){
long double c = (1.0 + (i / 1200.0)); //Finding the monthly percentage, and because the user inputs the yearly interest in %, we need to remove the %(*0.01) and /12 for 12 months/year.
return((1.0 + (n - 1)*c)*d*c); //The math formula that will give us the results of the calculation.
}
您使用的公式似乎是错误的 - 但我不确定您从哪里得到它或它实际上代表什么。预期的答案是简单的定期复利。换句话说,每个月你都会计算newbalance = balance * (1 + annualrate/12) + deposit)
.在所需的三个月内迭代 3 次,得到的预期答案是 302.5069 美元,而不是您从公式中获得的较低值 302.0868 美元。
您使用的公式是错误的。
3个月末第一个月的存款价值:d.c^3
3个月末第二个月的存款价值:d.c^2
3个月末第三个月的存款价值:d.c
如果您将其推广到 N 个月,则 N 个月结束时您的存款总价值将为:
d(c + c^2 + c^3 + ... + c^N)
该总和的值为:d.c.(c^N - 1)/(c-1)
如果你插入这个公式,你会得到正确的答案:302.507
。
公式
sum = d(c + c^2 + c^3 + ... + c^N)
将两边乘以c
,
sum.c = d(c^2 + c^3 + c^4 + ... + c^(N+1))
减去两个方程,
sum(c-1) = d(c^(N+1) - c) = d.c(c^N - 1)
sum = d.c(c^N - 1)/(c-1)