首先,这是一个课堂作业,所以我会很感激帮助,但只是提示,因为我想学习.我必须根据我的代码中的利率等计算每月付款,但我的计算结果不合适.我的输出读取nan我相信的not a number.我一直试图弄清楚我哪里出错无济于事,有关如何纠正这个问题的任何建议?提前致谢.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
//collect payment info
double loanAmount = 0;
double anualRate = 0;
double monthlyIntRate = 0;
int numOfPayment = 0;
double monthlyPayment = 0;
double amountPaidBack = 0;
double interestPaid = 0;
cout << "Enter loan amount: ";
cin >> loanAmount;
cout << "Enter Anual Interest Rate: ";
cin >> anualRate;
cout << "Enter Payments made: ";
cin >> numOfPayment;
//calculate montly payment
monthlyPayment = (loanAmount * pow(monthlyIntRate + 1, numOfPayment) * monthlyIntRate) / ( pow(monthlyIntRate + 1, numOfPayment) - 1);
//calculate amount paid back
amountPaidBack = monthlyPayment * numOfPayment;
//calculate interest paid
monthlyIntRate = anualRate / 12;
interestPaid = monthlyIntRate * numOfPayment;
//split input from calculated output
cout << "-----------------------------\n" << endl;
//Display the calulated data
cout << fixed;
cout << setprecision(2);
cout << "Loan Amount: " << setw(15) << "$ "<< right << loanAmount << endl;
cout << "Monthly Interest Rate: " << setw(14) << monthlyIntRate << "%" << endl;
cout << "Number of Payments: " << setw(17) << numOfPayment << endl;
cout << "Montly Payment: " << setw(19) << "$ " << monthlyPayment << endl;
cout << "Amount Paid Back: " << setw(17) << "$ " << amountPaidBack << endl;
cout << "Interest Paid: " << setw(18) << "$ " << interestPaid << endl;
return 0;
Run Code Online (Sandbox Code Playgroud)
输出:
Loan Amount: $ 100000.00
Monthly Interest Rate: 1.00%
Number of Payments: 36
Montly Payment: $ nan
Amount Paid Back: $ nan
Interest Paid: $ 36.00
Run Code Online (Sandbox Code Playgroud)
你除以零.它发生在这一行:
monthlyPayment = (loanAmount * pow(monthlyIntRate + 1, numOfPayment) * monthlyIntRate) / ( pow(monthlyIntRate + 1, numOfPayment) - 1);
Run Code Online (Sandbox Code Playgroud)
存储的值monthlyIntRate为零,因此pow(monthlyIntRate + 1, numOfPayment)eqauls为(0 + 1) ^ numOfPayment,因此pow(monthlyIntRate + 1, numOfPayment) - 1)为0.
正如@FlopCoder所提到的,按时间monthlyPayment计算,monthlyIntRate == 0.所以分数的除数
monthlyPayment = (loanAmount * pow(monthlyIntRate + 1, numOfPayment) * monthlyIntRate) / ( pow(monthlyIntRate + 1, numOfPayment) - 1);
Run Code Online (Sandbox Code Playgroud)
是0.
但这还不够nan.如果股息不是0,你会得到inf.但是你的情况也是 0.然后,你明白了nan.
| 归档时间: |
|
| 查看次数: |
13952 次 |
| 最近记录: |