C ++将2d数组传递给函数

时间:2016-08-22 05:47:15

标签: c++ arrays function

理解计算我们需要在下面声明一个函数的数组的平均值。循环并逐行读取。

double getAverage(int arr[], int size)
{
  int    i, sum = 0;       
  double avg;          

  for (i = 0; i < size; ++i){
    sum += arr[i];
   }

  avg = double(sum) / size;    
  return avg;
}

之后我们将值调用为main。

#include <iostream>
using namespace std;

// function declaration:
double getAverage(int arr[], int size);

int main ()
{
   // an int array with 5 elements.
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   // pass pointer to the array as an argument.
   avg = getAverage( balance, 5 ) ;

   // output the returned value 
   cout << "Average value is: " << avg << endl; 

   return 0;
}

所以我的问题是,如果我想计算行* col的平均值怎么办?我要宣布这样的事吗?假设row和col的大小是arr [3] [6]

double getAverage(int arr[][6], int noOfrows, int noOfcol)
{
    float sum=0, average;

    for (int i = 0 ; i < noOfrows ; i++) {
        for (int j = 0; j<noOfcol; j++) {    
        sum = sum + arr[i][j];    
        }
    }
        average = (float)sum / (float)(noOfcol*noOfrows);
        cout << "   " << average;

        return average; 
}

这是我的代码

int main()
{   
    int sales[3][6] = {{1000, 800, 780, 450, 600, 1200},
                       {800, 900, 500, 760, 890, 1000},
                        {450, 560, 570, 890, 600, 1100}};

    int avg;

    int choice;//menu choice

    const int computeAverage_choice = 1,
              computeTotal_choice = 2,
              listMaxMin_choice = 3,
              Exit_choice = 4;

    do
    {   
            //displayMenu(); // Show Welcome screen
            choice = displayMenu();
            while (choice < 1 || choice > 4)
         {
               cout << "Please enter a valid menu choice: " ;
               cin >> choice;
         }

            //If user does not want to quit, proceed.
         if (choice != Exit_choice)
         {  

                    switch (choice)
                    {
                           case computeAverage_choice:
                                avg = computeAverage(sales, 3, 6);
                                cout<<"The averge:" << avg;

                                break;

                           case computeTotal_choice:
                                //reserves
                                break;

                           case listMaxMin_choice:
                                //reserves
                                break;
                    }
         }
         } while (choice != Exit_choice);
            return 0;
}

4 个答案:

答案 0 :(得分:1)

如果您的函数声明如此:double getAverage(int arr[][6], int noOfrows, int noOfcol) 但是您尝试使用avg = getAverage( balance, 5 ) ; [仅2个参数]调用它,您的编译器应该返回错误。< / p>

只需将您的通话调整为avg = getAverage( balance, 5 */num or rows*/ , 6 */num of cols*/) ;

即可
#include <iostream>
using namespace std;

 double getAverage(int arr[][6], int noOfrows, int noOfcol)
{
    float sum=0, average;

    for (int i = 0 ; i < noOfrows ; i++) {
        for (int j = 0; j<noOfcol; j++) {

        sum = sum + arr[i][j];

        }
    }
        average = (float)sum / (float)(noOfcol*noOfrows);
        cout << "   " << average;

        return average; 
}


 int main()
 {
    int a[2][6] = {{1,2,3,4,5,6},{2,3,4,5,6,7}};
    getAverage(a, 2, 6);   // OK
    getAverage( a, 5 ) ;   // compile error
    return 0;
 }

答案 1 :(得分:0)

&#34;我要宣布这样的事情吗?&#34;

是。这就是你如何声明一个带有六个int数组的函数。

如果不知道大小,有两种方法可以解决它:使用std::vector(或者在数组数组的情况下,使用矢量矢量)。或者,您可以使用 templates 作为数组行和列:

template<size_t noOfrows, size_t noOfcol>
int getAverage(int const (&arr)[noOfrows][noOfcol])
{
    ...
}

这样你只需要用数组作为参数调用它,行和列的数量将由编译器推导出来:

int balance1[4][7] = { ... };
int average1 = getAverage(balance1);

int balance2[2][5] = { ... };
int average2 = getAverage(balance2);

无论数组大小还是子数组,它都可以工作。

答案 2 :(得分:0)

我的问题对我来说还不清楚。如果您担心声明行和列并将其传递给函数,则可以通过将数组作为参数传递或将指向数组的指针作为参数来实现。 我在#define中定义了行和列的长度。

解释

#include <iostream>
using namespace std;
#define NO_OF_ROWS 2
#define NO_OF_COLS 3

主要功能

int main ()
{
// an int array with 5 elements
int balance[5] = {1000, 2, 3, 17, 50};
int ar[2][3] = {{5,5,5},{10,10,10}};
double avg, avgRC;

// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;
avgRC = getAvg(ar);
// output the returned value 
cout << "Average value is: " << avg << endl; 
cout << "Average of row*col: " << avgRC << endl;

return 0;
}

GetAvg函数返回row * col average

double getAvg(int arr[][NO_OF_COLS])
{
 float sum=0, average;

   for (int i = 0 ; i < NO_OF_ROWS ; i++) {
    for (int j = 0; j<NO_OF_COLS; j++) {

    sum = sum + arr[i][j];

    }
 }
    average = (float)sum / (float)(NO_OF_ROWS*NO_OF_COLS);
    cout << "   " << average;
    return average; 

}

答案 3 :(得分:0)

int sales[3][6]的布局相同int sales[3 * 6],您可以重复使用之前的代码,只需调用

const double avg = getAverage(&sales[0][0], 3 * 6);

如果你想传递数组,最好的方法是通过引用传递(使用非直观的语法)并让模板推断出大小:

template <std::size_t R, std::size_t  C>
double getAverage(const int (&a)[R][C]) {
    return std::accumulate(&a[0][0], &a[0][0] + R * C, 0.) / (R * C);
}