计算结果始终为0

问题描述 投票:0回答:1

我正在模拟贷款支付计算器,并且确定使用了正确的方程式和数据类型。我是否缺少数据类型转换之类的东西?我是否正在做C ++不允许的操作?

我尝试对方程式中的变量重新排序,更改变量和函数的数据类型,将方程式移出函数之外。

float annualInterestRate,
       payment,
       periodRate = annualInterestRate / 1200.0;

int loanAmount,
    years,
    months = years * 12;

int mortgageLoanMinimum = 100000,
    carLoanMinimum = 5000,
    carLoanMaximum = 200000;

float mortgageRateMinimum = 2.0,
       mortgageRateMaximum = 12.0,
       carRateMinimum = 0.0,
       carRateMaximum = 15.0;

int mortgageTermMinimum = 15,
    mortgageTermMaximum = 30,
    carTermMinimum = 3,
    carTermMaximum = 6;
float mortgage() {

    cout << "How much money do you want to borrow? (Nothing less than $100,000): ";
    cin >> loanAmount;
    cout << "How much annual interest rate by percent? (2.0% - 12.0%): ";
    cin >> annualInterestRate;
    cout << "For how many years? (15 - 30 Years): ";
    cin >> years;

    payment = (loanAmount * periodRate * pow((1 + periodRate), months)) / (pow((1 + periodRate), months));



    return(payment);

}

[选择抵押时,输入5​​00000作为creditAmount,输入4.5作为AnnualInterestRate,并输入30多年,我期望付款为2533.80,但始终为0。

c++ calculation cmath
1个回答
0
投票

全局变量在C ++中初始化为0。

执行时

int loanAmount,
years,
months = years * 12;

[years初始化为0,并且months初始化为0 * 12 =0。由于您从未将months的值更新为不为0,因此计算将始终为0。


0
投票

float annualInterestRate,
       payment,
       periodRate = annualInterestRate / 1200.0;

int loanAmount,
    years,
    months = years * 12;

不要做我想让他们做的事。

[periodicRatemonths被初始化为0。但是,当您从用户输入读取annualInterestRateyears的值时,它们不会被更新。

读取periodicRatemonths后需要计算annualInterestRateyears。>

float mortgage() {

    cout << "How much money do you want to borrow? (Nothing less than $100,000): ";
    cin >> loanAmount;
    cout << "How much annual interest rate by percent? (2.0% - 12.0%): ";
    cin >> annualInterestRate;
    cout << "For how many years? (15 - 30 Years): ";
    cin >> years;

    float periodRate = annualInterestRate / 1200.0;
    int months = years * 12;

    payment = (loanAmount * periodRate * pow((1 + periodRate), months)) / (pow((1 + periodRate), months));

    return(payment);
}

通过适当的更改,您可以删除全局变量periodicRatemonths

© www.soinside.com 2019 - 2024. All rights reserved.