计算结果始终为0

Result of calculation is always 0

我正在模拟贷款支付计算器,我确信我使用了正确的方程式和数据类型。我是否缺少数据类型转换之类的?我在做 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 0,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);

}

选择抵押贷款时,贷款金额输入 500000,年利率输入 4.5,年限输入 30,我预计还款额为 2533.80,但始终为 0。

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

当你这样做时

int loanAmount,
years,
months = years * 12;

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

线条

float annualInterestRate,
       payment,
       periodRate = annualInterestRate / 1200.0;

int loanAmount,
    years,
    months = years * 12;

不要做我认为你想让他们做的事。

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

您需要在读取 annualInterestRateyears 之后计算 periodicRatemonths

float mortgage() {

    cout << "How much money do you want to borrow? (Nothing less than 0,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

我怀疑你误会了

months = years * 12;

确实有效。

执行该语句时,它会将 months 的值设置为 years 当前值的 12 倍。它不会告诉计算机月份应该 总是 years 值的 12 倍。现在,当语句运行时,years 的值尚未设置,因此 years * 12 == 0.

您可以通过在获取 years 的用户输入后为 months 赋值或将计算中的 months 替换为 12 * years 来修复您的代码。

您将 periodRate 声明为

periodRate = annualInterestRate / 1200.0;

但是,声明periodRate时,annulaInterestRate是编译器初始化的值,即0.0f,也就是periodRate = 0.0f。这里,需要使用define

#define periodRate (annualInterestRate / 1200.0)

几个月也一样。

#define months (years * 12)