矩阵乘法

  static void Main(string[] args)
        {
            Console.WriteLine("请录入第一个数组:");
            double[,] arr1 = InputArr();
            Console.WriteLine("请录入第二个数组:");
            double[,] arr2 = InputArr();
            int rowsCount = arr1.GetLength(0);
            int colsCount = arr2.GetLength(1);
            int comCount = arr1.GetLength(1);
            int[,] result = new int[rowsCount, colsCount];
            Console.WriteLine("两个数组的乘积为:");
            for (int i = 0; i < rowsCount; i++)
            {
                for (int j = 0; j < colsCount; j++)
                {
                    Console.Write("\t{0}", GetResult(i, j, comCount, arr1, arr2));
                }
                Console.WriteLine();
            }
            Console.ReadLine();

        }
        private static double[,] InputArr()
        {
            try
            {
                Console.WriteLine("请输入数组结构,例如:4,2");
                string[] arrLen = Console.ReadLine().Split(',');
                int rowsLen = Convert.ToInt32(arrLen[0]);
                int colsLen = Convert.ToInt32(arrLen[1]);
                double[,] result = new double[rowsLen, colsLen];
                Console.WriteLine("请输入每一行数据,例如:1,2,3,4,7,8");
                for (int i = 0; i < rowsLen; i++)
                {
                    string[] row = Console.ReadLine().Split(',');
                    for (int j = 0; j < colsLen; j++)
                    {
                        result[i, j] = Convert.ToDouble(row[j]);
                    }
                }
                Console.WriteLine("数组录入完成:");
                for (int i = 0; i < rowsLen; i++)
                {
                    for (int j = 0; j < colsLen; j++)
                    {
                        Console.Write("\t{0}", result[i, j]);
                    }
                    Console.WriteLine();
                }
                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine("数据录入异常!");
                return null;
            }

        }
        private static double GetResult(int row, int col, int len, double[,] arr1, double[,] arr2)
        {
            double result = 0;
            for (int temp = 0; temp < len; temp++)
            {
                result += arr1[row, temp] * arr2[temp, col];
            }
            return result;
        }

 

posted @ 2013-12-09 11:50  Everglow  阅读(198)  评论(0编辑  收藏  举报