摘要介绍矩阵的编程表示,矩阵的初等变换,化阶梯矩阵及求方阵的行列式。 矩阵介绍矩阵就是一个M×N平面的表格,用一个两维数组就可以表示,为了输入方便,我们用一个特殊格式的字符串对矩阵进行初始化,用"|"分割每一行,用","分割每一列,并增加一个Show的方法打印出矩阵,为了测试及调试的需要,还重写了ToString()方法。 - public class Matrix {
- public int M { get; private set; }
- public int N { get; private set; }
- private readonly double[,] num = null;
- #region 构造函数/Show
- public Matrix(int m, int n, string input) {
- M = m;
- N = n;
- num = new double[m, n];
- if (!string.IsNullOrEmpty(input))
- parseInput(input);
- }
- private void parseInput(string input) {
- string[] rows = input.Split(new[] { '|' });
- if (rows.Length != M)
- throw new ArgumentException("row count err");
- for (int i = 0; i < M; i++) {
- string row = rows;
- string[] cells = row.Split(new[] { ',' });
- if (cells.Length != N)
- throw new ArgumentException(string.Format("cells counte err:{0}", row));
- for (int j = 0; j < N; j++) {
- int cellValue;
- if (!int.TryParse(cells[j], out cellValue))
- throw new ArgumentException(string.Format("cell error:{0}", cells[j]));
- num[i, j] = cellValue;
- }
- }
- }
- public void Show() {
- for (int i = 0; i < M; i++) {
- for (int j = 0; j < N; j++)
- Console.Write("{0}\t", num[i, j]);
- Console.WriteLine();
- }
- }
-
- public override string ToString() {
- StringBuilder sb = new StringBuilder();
- for (int i = 0; i < M; i++) {
- for (int j = 0; j < N; j++) {
- sb.Append(num[i, j]);
- if (j != N - 1)
- sb.Append(',');
- }
- if (i != M - 1)
- sb.Append('|');
- }
- return sb.ToString();
- }
- }
复制代码先对这些代码进行单元测试,为了让代码块覆盖率达到{bfb},对构造函数的测试要故意模拟错误的输入,以便覆盖抛出异常的语句。 - [TestMethod()]
- public void MatrixConstructorTest() {
- Matrix m;
- try
- {
- m = new Matrix(2,2,"1,2|3,4|5,6");
- Assert.Fail();
- }
- catch{}
- try {
- m = new Matrix(2, 2, "1,2|3,4,5");
- Assert.Fail();
- }
- catch { }
- try {
- m = new Matrix(2, 2, "1,2|3,a");
- Assert.Fail();
- }
- catch { }
- }
- [TestMethod]
- public void toStringTest()
- {
- Matrix matrix = new Matrix(3, 3, "1,2,3|4,5,6|7,8,9");
- Assert.IsTrue(matrix.ToString() == "1,2,3|4,5,6|7,8,9");
- }
- [TestMethod()]
- public void ShowTest() {
- Matrix matrix = new Matrix(2, 2, "1,2|3,4");
- matrix.Show();
- //这玩意还真没法儿测,不出错就算成功
- }
复制代码
|