【问题标题】:c++ Find average of negatives with functionc++ 用函数求负数的平均值
【发布时间】:2015-12-15 19:42:22
【问题描述】:

当我把所有东西都放在main 中时,这个查找负元素平均值的代码可以正常工作。问题是当我尝试将其拆分为功能时。如何连接 cinarraynegative_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;
        }
    }
}

还有一件事为什么错误列表显示我需要“;”

int negative_average()
{ //here
    int negCount = 0;
    int average = 0;

【问题讨论】:

  • 谁给了 +1 !!!

标签: c++ arrays function average


【解决方案1】:

首先,您不能在另一个函数的主体中定义一个函数,这就是“; 这里需要”错误的原因。将其移至全局范围。在这种情况下,您可以在main 中创建int A[3][3];,并相应地声明您的函数:

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

然后将A 传递给两者。

【讨论】:

  • 数组不需要显式通过引用传递,它总是通过引用传递
【解决方案2】:

作为一个选项,在 main 中定义数组并传递对 cinarray()negative_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])

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2022-11-19
      • 1970-01-01
      • 2015-01-29
      • 2022-08-18
      • 2020-09-14
      • 2015-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多