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} };
答案 0 :(得分:0)
我修改了你的原型。
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 ? ',' : '\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;
}