gpt4 book ai didi

c++ - 程序和计算器答案之间的 0.5 差异

转载 作者:行者123 更新时间:2023-11-30 01:50:08 25 4
gpt4 key购买 nike

我用 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.
}

最佳答案

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

关于c++ - 程序和计算器答案之间的 0.5 差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27969928/

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