【发布时间】:2019-11-12 20:00:51
【问题描述】:
我用 C++ 编写了这段代码,以从文件中读取二维数组。现在我想用函数更好地组织我的代码。我遇到的问题是我无法弄清楚如何将加载到内存中的二维数组传递给同一程序中的另一个函数。 这是我需要组织成函数的代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define M 4
#define N 4
int main(){
int i, j;
float A[M][N];
string line;
ifstream matrix("matrix.txt");
if (matrix.is_open())
{
do
{
for(i=0; i<M; i++)
{
for(j=0; j<N; j++)
matrix >> A[i][j];
}
}
while (getline(matrix,line));
matrix.close();
}
else cout << "Unable to open file";
float sumline[M]={0};
for(i=0;i<M;i++)
{
for(j=0;j<N;j++)
sumline[i]+=A[i][j];
}
float sumcolumn[N]={0};
for(j=0;j<N;j++)
{
for(i=0;i<M;i++)
sumcolumn[j]+=A[i][j];
}
for (i=0; i<M; i++){
for (j=0; j<N; j++){
if(sumline[i]<sumcolumn[j]){
cout << "Error, total sum of column "<<j<<" is greater than the sum of the line"<<i<<endl;
return 0;
}
}
}
int mincol=sumcolumn[0];
for (i=0; i<N; i++){
if(mincol>sumcolumn[i])
mincol==sumcolumn[i];
}
float avgline = 0.0;
for (i=0; i<M; i++){
avgline=avgline+sumline[i];
}
avgline = avgline/M;
if (avgline * 3 > mincol) {
cout << "Conditions verified"<<endl;
}
else{
cout << "Error, triple of the avg of line is less than the lowest sum of column"<<endl;
return 0;
}
return 0;
}
代码基本上对二维数组进行了一些数学运算。我也想尽可能简单,所以即使using namespace std; 这不是一个很好的做法,或者我从文件中读取数组的方式非常基本,我也需要它是这样的。非常感谢。
【问题讨论】:
-
您似乎想要code review?
-
作为解决将矩阵轻松传递给函数的问题的提示,请考虑使用
std::array而不是 C 样式的数组。 -
我写下的代码按预期工作。我想全面了解我需要做什么以及我正在处理什么样的代码。如果我有更多问题,我会看看标准数组函数并回复你。感谢您的回复。
-
所以,我一直在研究这个函数,它是一种更 C++ 的处理数组的方式。但我仍然无法回答的问题基本上是这个问题:我正在构建从文件读取的二维数组,所以我在同一个函数中传递所有值。现在我应该有什么样的功能来
return二维数组?它不能只是一个float函数。我唯一能想到的就是从main()传递数组值,但这不是我想的那样。 -
使用来自the answer by darune 的类型别名,只要返回类型为
MyArrayType?
标签: c++ function multidimensional-array