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

C++ : Value passed through function parameters is giving different result

本文关键字:结果 C++ 函数 参数传递      更新时间:2023-10-16

我遇到了一个似乎无法弄清楚的问题。我正在写一个抵押贷款计算器,我正在逐步分解它,因为第一个结果不起作用。但是,我在使用值 250000 初始化函数时遇到问题。如果我运行它,它最终会给我 12500 与 1250,这是正确答案。

我添加了 cout <<250000 * 每月费率<<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;
}

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

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

在函数中,您拥有:

return 0;

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

return principal * monthlyRate;

并删除函数内的所有打印件。