C++编译器不允许我使用数组作为参数来调用用户定义的函数

C++ compiler not letting me use an array as parameter to function call in a userdefined function

本文关键字:调用 参数 用户 定义 函数 不允许 编译器 允许我 数组 C++      更新时间:2023-10-16

C++编译器不允许我在用户定义的函数中使用数组作为函数调用的参数。有人可以向我解释这一点并帮助我解决问题吗?

#include <iostream>
using namespace std;
double GetAverage(int[], int = 10);
int GetAboveAverage(int[], int = 10);
const int ARRAYSIZE = 10;
void main()
{
    int mArray[ARRAYSIZE];
    cout << "Input the first number" << endl;
    for (int i = 0; i <= ARRAYSIZE - 1; i++)
    {
        cin >> mArray[i];
        cout << "Input the next number" << endl;
    }
    cout << "The average of the nummbers is " << GetAverage(mArray, ARRAYSIZE) << endl;
    cout <<"The the amount above average is " << GetAboveAverage(mArray, ARRAYSIZE) <<endl;
    system("pause");
}

问题所在的函数调用此函数。

double GetAverage(int fArray[], int arrSize)
{
    int sum = 0;
    int average;
    for (int i = 0; i <= arrSize- 1; i++)
    sum += fArray[i];
    average = sum / arrSize;
    return average;
}

听觉是问题所在。

int GetAboveAverage(int gArray[], int arrSize)
{
    int amtAboveAve;
    int average = GetAverage( gArray[], arrSize); //where i get the error its on the bracket and it says "error: expected and expression"
    for (int i = 0; i <= 9; i++)
        if (gArray[i] > average)
            amtAboveAve++;
    return amtAboveAve;
}

您不能按原样传递gArray[]因为它在您尝试使用它的上下文中毫无意义。这是因为gArray[]尝试将参数列表声明为声明,其中不能作为函数中的参数传递。

您可能会因此而得到的确切错误是:

错误

#[此处为错误号]:需要表达式

函数声明需要表达式,而不是声明

相反,只需在函数声明中使用不带括号的gArray

数组传递给函数时不要包含括号。

替换此内容:

    int average = GetAverage( gArray[], arrSize); 

有了这个:

    int average = GetAverage( gArray, arrSize);