C++ c++;用函数求负数的平均值

C++ c++;用函数求负数的平均值,c++,arrays,function,average,C++,Arrays,Function,Average,当我将所有内容都放在main中时,查找负元素平均值的代码运行良好。问题是当我尝试将它拆分为函数时。如何连接cinarray和negative\u average函数中的元素 #include <iostream> using namespace std; int main() { cinarray(); negative_average(); } int cinarray() { int A[3][3]; int i, j; for (i

当我将所有内容都放在
main
中时,查找负元素平均值的代码运行良好。问题是当我尝试将它拆分为函数时。如何连接
cinarray
negative\u average
函数中的元素

#include <iostream>

using namespace std;
int main()
{
    cinarray();
    negative_average();
}

int cinarray()
{
    int A[3][3];
    int i, j;

    for (i = 0; i < 3; i++)
        for (j = 0; j < 3; j++) {
            cout << "\n A[" << i + 1 << "][" << j + 1 << "]=";
            cin >> A[i][j];
        }

    for (i = 0; i < 3; i++) {
        for (j = 0; j < 3; j++)
            cout << A[i][j] << "\t";

        cout << "\n";
    }

    // compute average of only negative values
    int negative_average()
    {
        int negCount = 0;
        int average = 0;

        for (int x = 0; x < 3; ++x) {
            for (int y = 0; y < 3; ++y) {
                if (A[x][y] < 0) {
                    ++negCount;
                    average += A[x][y];
                }

            }
        }
        if (negCount > 0) {
            average /= negCount;
            cout << "Average of only negative values \n" << average;
        }
    }
}

作为一个选项,请在的main中定义数组,并将引用传递给
cinarray()
negative\u average()

这样做:

int main()
{
    int A[3][3];
    cinarray(A);
    negative_average(A);
    return 0;
}
其中:

int cinarray(int (&A)[3][3])
int negative_average(const int (&A)[3][3])

您的数组A对两个函数都不可见。您需要在main()中声明它,然后将它作为参数传递给其他函数。

首先,您不能在另一个函数体中定义函数,这就是为什么出现“
此处需要”错误的原因。将其移动到全局范围。在这种情况下,您可以创建
inta[3][3]main
中编写>并相应地声明函数:

void cinarray(int A[3][3]);                // why int return type?
void negative_average(const int A[3][3]);

然后将
A
传递给两者。

数组不必显式地通过引用传递,它总是通过引用传递,引用是谁给出的+1!!!
void cinarray(int A[3][3]);                // why int return type?
void negative_average(const int A[3][3]);