计算结果始终为0

时间:2019-10-04 04:35:12

标签: c++ calculation cmath

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

}

选择抵押贷款时,为creditAmount输入500000,为AnnualInterestRate输入4.5,为年输入30,我希望还款额为2533.80,但始终为0。

4 个答案:

答案 0 :(得分:0)

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

这样做的时候

int loanAmount,
years,
months = years * 12;

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

答案 1 :(得分: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

答案 2 :(得分:0)

我怀疑您误会了

months = years * 12;

实际上在工作。

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

您可以在获取months的用户输入后,通过为years分配一个值或用months替换计算中的12 * years来修正代码。

答案 3 :(得分:0)

您将periodRate声明为

periodRate = annualInterestRate / 1200.0;

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

#define periodRate (annualInterestRate / 1200.0)

几个月也一样。

#define months (years * 12)