如何使 getRowTotal 在二维数组的 C++ 中起作用
how to make getRowTotal function in C++ for two-dimensional array
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;
}
相关文章:
- 我的神经网络不起作用 [XOR 问题]
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- C++为什么尽管我调用了void函数,它却不起作用
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- Visual studio代码重构似乎不起作用(例如,重命名符号-f2)
- 为什么二进制搜索在我的测试中不起作用
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- Bjarne Stroustrup Book - std_lib_facilities.h - 不起作用(未知类型名称)
- 为什么简单的算术减法在"if"条件下不起作用?
- 为什么Stroustup书中的has_f不起作用
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 嵌套While循环不起作用(C++问题)
- C++Matching Brackets 2解决方案不起作用
- 为什么这段代码不起作用,我该如何解决?
- 我正在开发服务器,ip作为参数传递不起作用