程序和计算器答案之间的差异为0.5

时间:2015-01-15 17:57:29

标签: c++ visual-c++

我用C ++编写了这个程序,作为家庭作业的一部分,简单计算了银行的利率。答案是不正确的,但我仍然无法理解为什么,并且当我尝试更高的输入数字时错误变得更高...... 有关如何解决此问题的说明被注释为程序的第一行。

我尝试将涉及的变量从float切换到double然后再切换为long double,它仍然是相同的答案......

任何人都可以找出原因吗?

// 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 << "\n\nYou 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. 
}

2 个答案:

答案 0 :(得分:3)

您使用的公式似乎是错误的 - 但我不知道您在哪里获得它或它实际代表什么。预期的答案是简单的周期性复利。换句话说,您每月计算newbalance = balance * (1 + annualrate/12) + deposit)。在你需要的三个月内迭代3次,得到的预期答案为$ 302.5069,而不是从你的公式得到的较低值$ 302.0868。

答案 1 :(得分:1)

您使用的公式是错误的。

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)