作业帮 > 综合 > 作业

C#:完整程序应用代码:计算一个矩阵中每一列的平均值.

来源:学生作业帮 编辑:作业帮 分类:综合作业 时间:2024/05/18 08:08:09
C#:完整程序应用代码:计算一个矩阵中每一列的平均值.
public class Matrix { //矩阵类
private int _row;
private int _col;
private double[,] _matrix;
public Matrix(double[,] matrix) { //带参数的构造函数
_row = matrix.GetLength(0);
_col = matrix.GetLength(1);
_matrix = new double[_row,_col];
for (int r = 0; r < _row; r++) {
for (int c = 0; c < _col; c++) {
_matrix[r,c] = matrix[r,c];
}
}
}
public double[] GetAverageOfCol() { //取所有列的平均值函数
double[] averageOfCol = new double[_col];
for (int c = 0; c < _matrix.GetLength(0); c++) {
double sumaryOfCol = 0;
for (int r = 0; r < _matrix.GetLength(1); r++) {
sumaryOfCol += _matrix[r,c];
}
averageOfCol[c] = sumaryOfCol / _matrix.GetLength(1);
}
return averageOfCol;
}
}
//调用
static void Main() {
Matrix m = new Matrix(new double[,] { { 1,2,3 },{ 4,5,6 },{ 7,8,9 } });
double[] result = m.GetAverageOfCol();
//输出
string text = "";
for (int i = 0; i < result.GetLength(0); i++) {
text += result[i].ToString() + ",";
}
Console.WriteLine(text);
}