如何计算锯齿状阵列?

时间:2016-07-28 14:41:33

标签: c# jagged-arrays

我正在尝试使用锯齿状数组在c#中执行矩阵乘法程序。 代码跟随:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace JaggedMM
{
class Program
{
    static void Main(string[] args)
    {
        int r;
        Console.WriteLine("Enter the number of rows");
        r = Convert.ToInt32(Console.ReadLine());
        int[][] a = new int[r][];
        int[][] b = new int[r][];
        int[][] result = new int[r][];
        Console.WriteLine("First matrix");
        for (int i = 0; i < r; i++) {
            Console.WriteLine("Enter number of elements in" + i + "row:");
            int bc = Convert.ToInt32(Console.ReadLine());
            a[i] = new Int32[bc];
            for(int j = 0; j < bc; j++)
            {
                Console.WriteLine("Enter the elements in "+i+" row");
                a[i][j] = Convert.ToInt32(Console.ReadLine());
            }
        }
        for (int i = 0; i < r; i++) {
            for (int j = 0; j < a[i].Length; j++) {
                Console.Write(a[i][j] + "\t");
                Console.Write("\n");
            }
        }
        Console.WriteLine("Second matrix");
        for (int i = 0; i < r; i++)
        {
            Console.WriteLine("Enter number of elements in" + i + "row:");
            int bc1 = Convert.ToInt32(Console.ReadLine());
            b[i] = new Int32[bc1];
            for (int j = 0; j < bc1; j++)
            {
                Console.WriteLine("Enter the elements in " + i +  " row");
                b[i][j] = Convert.ToInt32(Console.ReadLine());
            }
        }
        for (int i = 0; i < r; i++)
        {
            for (int j = 0; j < b[i].Length; j++)
            {
                Console.Write(b[i][j] + "\t\n");
            }
        }
        for (int i = 0; i < r; i++) {
            for(int j = 0; j < a[i].Length && j<b[i].Length; j++)
            {
                result[i][j] = a[i][j]*b[j][i];
            }
        }
        for(int i = 0; i < r; i++)
        {
            for(int j = 0; j < a[i].Length && j<b[i].Length; j++)
            {
                Console.Write("The result is: \n"+result[i][j]+"\n\n");
            }
        }
    }
}
}

我有两个输入矩阵。问题是当我尝试计算那些矩阵的乘法时会得到一个systemNullException错误。

0 个答案:

没有答案