【发布时间】:2015-02-11 17:21:50
【问题描述】:
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 gArray[]是一个声明。传递给函数的参数是表达式,而不是声明。因此错误“期望一个表达式”。 -
哦,现在说得通了,我的编程老师决定赶这个单元。以太方式,非常感谢。
-
@RosarioPulella 我提供了答案。我刚刚意识到评论者在这里所说的或多或少是一样的,所以请点击投票按钮下方的绿色勾号将我的回答标记为已接受。
标签: c++ arrays user-defined-functions