我必須做一個程序,添加一個二維數組的列並返回最小的總和。這是我編寫的程序,但我想知道是否有更有效的方法。主要課程是由教授給我們的。我想知道是否有辦法做到這一點,而不必爲每列聲明一個整數,因爲如果它不總是3列,謝謝。如何在C++中總結二維數組中的列?
#include <iostream>
#include <string>
using namespace std;
int smallCol(int x[][3], int row, int col){
int c1 = 0;
int c2 = 0;
int c3 = 0;
int min;
for (int r = 0; r < row; r++){
for(int c = 0; c < col; c++){
if(c==0)
c1 += x[r][c];
if(c==1)
c2 += x[r][c];
if(c==2)
c3 += x[r][c];
}
}
min = c1;
if(c2 < c1)
min = c2;
if(c3 < c2)
min = c3;
return min;
}
int main() {
int x[2][3] = {{3, 1, 4}, {1, 5, 9}};
cout << "Smallest column sum is " << smallCol (x, 2, 3) << endl;
// from the 2-d array x that has size 2 x 3, find the smallest col sum
// output will be 4 since col#0 contains 3 and 1 is smallest.
return 0;
}
需要多長時間才能支持,哦,說2d陣列與100列?這是一個相對較小的2D陣列,你知道的。 –