在 2D 数组中添加列
Adding columns in a 2D array
我正在尝试将我拥有的每一列汇总到第 7 行,但我无法弄清楚如何显示以下内容:
100 101 102 103 104 105
106 107 108 109 110 111
112 113 114 115 116 117
118 119 120 121 122 123
124 125 126 127 128 131
560 565 570 575 580 587
此表的列需要汇总到数组的最后一行。这就是我想出的:
//Libraries
#include<ctime>
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
//Global constants
const int ROWS=7, COLS=7;
//function prototypes
void add(int [][COLS]);
void prntAry(int [][COLS]);
//execution begins here
int main(int argc, char** argv){
//Declare Variables
//fill array
int array[ROWS][COLS]={{100,101,102,103,104,105,0},
{106,107,108,109,110,111,0},
{112,113,114,115,116,117,0},
{118,119,120,121,122,123,0},
{124,125,126,127,128,131,0},
{0,0,0,0,0,0}};
add(array);
system("Pause");
return 0;
}
void add(int a[][COLS]){
cout<<endl;
int i=0;
for(i;i<ROWS;i++)
for(int row=0;row<ROWS;row++){
a[i][7]+=a[i][row];
}
prntAry(a);
}
void prntAry(int a[][COLS]){
cout<<endl;
for(int row=0;row<ROWS;row++){
for(int col=0;col<COLS;col++){
cout<<setw(4)<<a[row][col];
}
cout<<endl;
}
cout<<endl;
}
您一直显示到最后一列。 如果您只需要前 6 列
void prntAry(int a[][COLS]){
cout<<endl;
int lastcol = COLS - 1;
for(int row=0;row<ROWS;row++){
for(int col=0;col<lastcol;col++){
cout<<setw(4)<<a[row][col];
}
cout<<endl;
}
cout<<endl;
}
此外,在例程添加中,未正确索引
void add(int a[][COLS]){
cout << endl;
int lastcol = COL - 1;
for (int row = 0; row < ROWS; row++) {
for (int col = 0; col < lastcol; ++col)
a[row][lastcol] += a[row][col];
}
prntAry(a);
}
相关文章:
- 如何将元素添加到数组的线程安全函数?
- C++ 动态数组每次添加时将大小增加 1 - 错误
- 运算符重载 (+),用于添加两个具有 C++ 的数组
- 添加到数组指针
- 将随机生成的数字添加到数组 + 对这些数组求平均值
- 将数组的元素添加到链表中
- 如何在C++中将元素添加到非固定大小的数组中?
- 将在堆栈上声明的元素添加到静态数组
- const_cast静态数组以添加恒常性
- 在 char* 数组中添加两个索引
- c++ 如何在数组的开头添加值并为其编制索引?
- 检查数组中是否有字符串中的值,如果没有,则添加它
- 添加数组特定列的元素
- 添加数组元素:需要左键作为赋值的左操作数
- 添加数组所有元素的 SSE 指令
- 如何添加数组的偶数和奇数之和
- 向std::multimap添加数组值
- 用内部类函数递归地添加数组数
- 使用自增操作符添加数组元素
- 创建一个模板函数,如果数据类型不同,则添加数组的元素