C ++:通过函数参数传递的值给出不同的结果

Jul*_*tes -1 c++ double

我遇到了一个似乎无法解决的问题。我正在写抵押贷款计算器,并且由于第一个结果不起作用,所以我将逐步对其进行细分。但是,我在使用值250000初始化函数时遇到问题。如果运行它,最终会给我12500而不是1250,这是正确的答案。

我添加了cout << 250000 * monthRate << << endl; 检查这里是否有问题,但是如果我在main函数之前通过cout输入它,它也可以正确显示,并且也可以正常工作。有任何想法吗?

#include <iostream>
#include <cmath>
using namespace std;

double mortgageCalculator(double principal, double rate, double years);

int main()
{

    // local variables
    double principal, rate, years;

    cout << "How much is the principal amount" << endl;
    cin >> principal;
    // cout << "What is the yearly rate?" << endl;
    // cin >> rate;
    // cout << "Term of mortgage (years) " << endl;
    // cin >> years;

    cout << mortgageCalculator(25000, 6, 30) << endl;

    return 0;
}

double mortgageCalculator(double principal, double rate, double years)
{
    rate = rate / 100.0;
    cout << rate << endl;

     double result, monthlyRate = rate / 12.0;
    cout << monthlyRate << endl;

    result = principal * monthlyRate;
    cout << 250000 * monthlyRate << endl;
    cout << result;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Kev*_*vin 5

您正在打印出函数返回的内容:

cout << mortgageCalculator(25000, 6, 30) << endl;
Run Code Online (Sandbox Code Playgroud)

在函数中,您具有:

return 0;
Run Code Online (Sandbox Code Playgroud)

因此,您将打印出正确的结果(1250),然后加上0。看来您只想返回结果而不是在函数中将其打印出来。

return principal * monthlyRate;
Run Code Online (Sandbox Code Playgroud)

并删除功能内的所有打印件。