【问题标题】:How to calculate mean using calling function in C++?如何在 C++ 中使用调用函数计算平均值?
【发布时间】: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++


【解决方案1】:

函数getInputN 中的参数int n 隐藏(隐藏)全局变量n。这可以防止全局变量被更新,sum 被零除(没有显式初始化的 gloval 变量的默认值)。

如果您想使用 gloval 变量传递数据,则应删除参数,因为其中一个参数(n 如上所述)是有害的,而其他参数是多余的。

另外,函数displayData 被声明为返回float,但没有执行任何return 语句。这会调用未定义的行为。我通过将其返回类型更改为 void 来解决此问题。

#include <iostream>
using namespace std;

int getInputN();
float calculateMean ();
void displayData();

int i,n;
float sum = 0.0, num[50];
double mean;

int main()
{
    getInputN();
    calculateMean ();
    displayData();

    return 0;
}

int getInputN()
{
    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 ()
{

    mean = sum/n;

    return mean;
}

//function to display the mean
void displayData ()
{
    cout << "Average = " << mean;
}

此修复将使代码正常工作,但应该有更好的设计而不使用全局变量。 References 可用于让函数修改作为参数给出的内容,std::vector 可用于返回“数组”。

【讨论】:

  • 哦,好吧,我明白了...实际上在问题中,我的讲师说三个函数 getInput(N)、calculateMean() 和 displayData 接受参数。那么,它是如何在代码中实现的呢?顺便说一句,非常感谢您的回答!非常感谢。
【解决方案2】:

函数中使用int getInputN(int n) 中的变量n,而不是声明的全局n。因此,使用 global nuninitialized until that point 初始化为 0)来计算 mean = sum/n 将导致 undefined behavior罢工> divide by 0 错误,导致inf

更多信息:

另外,函数float displayData (double mean) 不返回任何值,导致另一个undefined behavior

更多信息:

修改后的代码:

#include <iostream>
using namespace std;

void getInputN();
void calculateMean();
void displayData();

int i,n;
float sum = 0.0, num[50];
double mean;

int main()
{
    getInputN();
    calculateMean();
    displayData();

    return 0;
}

void getInputN()
{
    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];
    }
}

//function to calculate the mean
void calculateMean ()
{
    mean = sum/n;
}

//function to display the mean
void displayData ()
{
    cout << "Average = " << mean;
}

结果:

Enter the numbers of data: 3
1. Enter number: 1
2. Enter number: 3
3. Enter number: 6
Average = 3.33333

此外,如果您不将这些数字用于其他任何用途,那么声明 float num[50]; 是毫无意义的。另外,注意不建议使用全局变量和using namespace std;

#include <iostream>

const int maxn = 50;
const int minn = 1;

int main()
{
    int n; std::cout << "Enter N : "; std::cin >> n;
    while (n < minn || n > maxn) {std::cout << "Invalid. Re-enter N : "; std::cin >> n;}

    double sum = 0; int tmp;
    for (int i = 0; i < n; i++) { std::cout << "Enter number " << i+1 << " : "; std::cin >> tmp; sum += tmp;}

    std::cout << "Average : " << sum/n;
}

结果:

Enter N : 3
Enter number 1 : 25
Enter number 2 : 97
Enter number 3 : 111
Average : 77.6667

【讨论】:

  • global n 具有静态存储持续时间,因此默认为零初始化。 (N3337 8.5 Initializers 9) mean = sum/n 调用 未定义的行为 因为它被零除。 (N3337 5.6 乘法运算符)
  • @MikeCAT 我的错,我现在要修改它。
  • 哦,好吧,我明白了...实际上在问题中,我的讲师说三个函数 getInput(N)、calculateMean() 和 displayData 接受参数。那么,它是如何在代码中实现的呢?顺便说一句,非常感谢您的回答!非常感谢。
  • @daisy98 如果您对函数的签名应该是什么以及它们应该如何工作有其他要求,请编辑实际问题以包含它们。否则人们将不得不猜测函数的预期行为是什么。
  • @daisy98 "其实在问题中,我的讲师说三个函数 getInput(N), calculateMean() & displayData 接受参数。”但是为了什么?好吧,我的意思是summeann 无论如何都是全局变量,并且可以被任何函数读取,所以float calculateMean (int n, float sum)float displayData (double mean) 的工作方式相同,int getInputN(int n) 会导致一些问题。那么你用这些参数for做什么呢?如果您有其他要求,请编辑您的问题以包含它们,否则,包含不必要的参数可能会导致混淆。
【解决方案3】:

了解函数的行为方式后,我们可以编写运行良好且完全不使用任何全局变量的实现。

#include <iostream>

double getInputN(int n);
double calculateMean(int n, double sum);
void displayData(double mean);

int main()
{   
    //User enter the number of value
    int numEntries;
    std::cout << "Enter the numbers of data: ";
    std::cin >> numEntries;

    //if user input more than 50 numbers
    while (numEntries > 50 || numEntries <= 0)
    {
        std::cout << "Invalid! Enter the number in range of (1 to 50)." << std::endl;
        std::cout << "Enter the number of data: ";
        std::cin >> numEntries;
    }

    // Get user input
    double sum = getInputN(numEntries);

    double mean = calculateMean(numEntries, sum);

    displayData(mean);

    return 0;
}

double getInputN(int n)
{
    double sum = 0.;

    for (int i = 0; i < n; ++i)
    {
        double userInput;
        std::cout << i + 1 << ". Enter number: ";
        std::cin >> userInput;
        sum += userInput;
    }

    return sum;
}

//function to calculate the mean
double calculateMean(int n, double sum)
{

    double mean = sum / n;

    return mean;
}

//function to display the mean
void displayData(double mean)
{
    std::cout << "Average = " << mean;
}

让我们更详细地了解每个更改。

首先,我更改了所有函数的签名。 getInputN 应该返回 double,而不是 intcalculateMean 应该接受并返回 double,而不是 float。而displayData 不需要返回任何东西,它返回任何东西没有意义,因此我将它的返回类型设为void

其次,请注意,我已将用于计算要输入多少条目的代码从getInputN 移至main。原因是getInputN 的唯一参数是“我们应该获得多少输入?”,所以我们需要知道它的值我们调用getInputN

第三,注意我是如何在调用代码中使用每个函数的返回值的。在main 中,当我编写double sum = getInputN(numEntries); 时,它声明了一个变量sum 并将getInputN(numEntries) 的返回值存储到sum。当你只写getInputN(n); 时,getInputN 的返回值将被丢弃。通过将其存储在main 的变量中,我可以将其值传递给另一个函数,例如在我编写double mean = calculateMean(numEntries, sum); 的下一行中。

第四,请注意问题的要求如何使我不再使用任何类型的数组。 getInputN 不会费心跟踪每个条目,因为我们只关心最后的最终总和。

【讨论】:

  • @daisy98 这听起来像是您的环境的问题。也许this question 会有所帮助?
  • 哦,我明白了!错误来自我,对不起。非常感谢你从一开始就帮助我 :) 真的很感激!
猜你喜欢
  • 1970-01-01
  • 2017-09-26
  • 1970-01-01
  • 2020-07-26
  • 2020-10-31
  • 2021-09-06
  • 2022-11-14
  • 1970-01-01
  • 2021-02-14
相关资源
最近更新 更多