如何使 getRowTotal 在二维数组的 C++ 中起作用

how to make getRowTotal function in C++ for two-dimensional array

本文关键字:C++ 起作用 二维数组 何使 getRowTotal      更新时间:2023-10-16

getRowTotal.此函数应接受二维数组作为其第一个参数,接受整数作为其第二个参数。第二个参数应该是数组中一行的下标。该函数应返回指定行中值的总和。

如何在C++中构建此功能?

这是我正在使用的:

#include <iostream>
#include <iomanip>
using namespace std;
//declare global variables
const int NUM_ROWS = 3;
const int NUM_COLS = 3;
//prototypes
void showArray(int array[][NUM_COLS], int);
int getTotal(int [][NUM_COLS], int, int);
int getAverage(int [][NUM_COLS], int, int);
int getRowTotal(int [][NUM_COLS], int, int);

int main() {
    int total = 0;
    int average = 0;
    int rowTotal = 0;
    int smallArray[NUM_ROWS][NUM_COLS] = { {1, 2, 3},
                                            {4, 5, 6},
                                            {7, 8, 9} };
    int largeArray[NUM_ROWS][NUM_COLS] = { {10, 20, 30},
                                            {40, 50, 60},
                                            {70, 80, 90} };

我已经修改了你的原型。

void showArray( int array[NUM_ROWS][NUM_COLS] )
{
  for( int i = 0; i < NUM_ROWS; ++i )
  {
    for( int j = 0; j < NUM_COLS; ++j )
      std::cout << (j > 0 ? ',' : '') << array[i][j];
    std::cout << std::endl;
  }
}
int getTotal( int array[NUM_ROWS][NUM_COLS] )
{
  int total = 0;
  for( int i = 0; i < NUM_ROWS; ++i )
  for( int j = 0; j < NUM_COLS; ++j )
    total += array[i][j];
  return total;
}
int getAverage( int array[NUM_ROWS][NUM_COLS] )
{
  return getTotal( array )/(NUM_ROWS * NUM_COLS);
}
int getRowTotal( int array[NUM_ROWS][NUM_COLS], int row )
{
  int total = 0;
  if( (row >= 0) && (row < NUM_ROWS) )
  {
    for( int j = 0; j < NUM_COLS; ++j )
      total += array[row][j];
  }
  return total;
}