【发布时间】:2021-06-12 00:05:55
【问题描述】:
函数是getInputN()、calculateMean()和displayData()。
所以要明确地说,这些是要求。
-
getInputN函数:应该接受值的个数,N作为一个整数作为参数,并要求用户输入N个数字的值。然后,将值的总和作为双精度值返回。 -
calculateMean函数:应该接受值的个数、N 和值的总和作为参数。然后将平均值作为双精度值返回。 -
displayData函数:应该接受均值作为参数。然后,将它们显示在屏幕上的相应消息中。此函数不需要返回值。
如果我运行代码,它将显示 Average = inf
p/s:对于这个令人困惑的问题,我真的很抱歉。我对这个网站真的很陌生,这是我的第一个问题。我花了一些时间才弄清楚在这个平台上要正确提出的问题。希望大家谅解,再次对给您带来的不便深表歉意。也谢谢你的帮助:)
这是我的代码:
#include <iostream>
using namespace std;
int getInputN(int n);
float calculateMean (int n, float sum);
float displayData(double mean);
int i,n;
float sum = 0.0, num[50];
double mean;
int main()
{
getInputN(n);
calculateMean (n, sum);
displayData(mean);
return 0;
}
int getInputN(int n)
{
int i;
float num[50];
//User enter the number of value
cout << "Enter the numbers of data: ";
cin >> n;
//if user input more than 50 numbers
while (n > 50 || n <= 0)
{
cout << "Invalid! Enter the number in range of (1 to 50)." << endl;
cout << "Enter the number of data: ";
cin >> n;
}
for(i = 0; i < n; ++i)
{
cout << i + 1 << ". Enter number: ";
cin >> num[i];
sum += num[i];
}
return n;
}
//function to calculate the mean
float calculateMean (int n, float sum)
{
mean = sum/n;
return mean;
}
//function to display the mean
float displayData (double mean)
{
cout << "Average = " << mean;
}
【问题讨论】:
-
有什么错误?
-
停止使用全局变量永远不会太早。
-
getInputN中的参数int n会影响全局int n。所以getInputN不会更新全局变量,它只是返回一个值。因此,当您使用全局n作为参数调用calculateMean(n, sum)时,它没有任何有效值。您的函数具有返回类型,您应该在调用代码中使用它们。 -
calculateMean 将一个总和(你从未添加任何东西,所以它为零)除以一个你从未初始化过的数字 n。看起来你似乎还没有真正理解如何使用返回值。
-
我得到的输出是Average = inf。答案应该得到输入数字的平均值。我认为参数和返回值都搞砸了lol
标签: c++