C#程序添加两个矩阵
首先,设置三个数组。
int[, ] arr1 = new int[20, 20]; int[, ] arr2 = new int[20, 20]; int[, ] arr3 = new int[20, 20];
现在,用户将在两个矩阵中输入值。我们必须将行和大小列设置为n=3,因为我们想要一个3x3大小的方阵,即9个元素。
将两个矩阵相加,并打印出具有总和的第三个数组。
for(i=0;i<n;i++) for(j=0;j<n;j++) arr3[i,j]=arr1[i,j]+arr2[i,j];
以下是在C#中添加两个矩阵的完整代码。
示例
using System; public class Exercise19 { public static void Main() { int i, j, n; int[, ] arr1 = new int[20, 20]; int[, ] arr2 = new int[20, 20]; int[, ] arr3 = new int[20, 20]; //设置矩阵行和列的大小 n = 3; Console.Write("Enter elements in the first matrix:\n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { arr1[i, j] = Convert.ToInt32(Console.ReadLine()); } } Console.Write("Enter elements in the second matrix:\n"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { arr2[i, j] = Convert.ToInt32(Console.ReadLine()); } } Console.Write("\nFirst matrix is:\n"); for (i = 0; i < n; i++) { Console.Write("\n"); for (j = 0; j < n; j++) Console.Write("{0}\t", arr1[i, j]); } Console.Write("\nSecond matrix is:\n"); for (i = 0; i < n; i++) { Console.Write("\n"); for (j = 0; j < n; j++) Console.Write("{0}\t", arr2[i, j]); } for (i = 0; i < n; i++) for (j = 0; j < n; j++) arr3[i, j] = arr1[i, j] + arr2[i, j]; Console.Write("\nAdding two matrices: \n"); for (i = 0; i < n; i++) { Console.Write("\n"); for (j = 0; j < n; j++) Console.Write("{0}\t", arr3[i, j]); } Console.Write("\n\n"); } }
输出结果
Enter elements in the first matrix: Enter elements in the second matrix: First matrix is: 000 000 000 Second matrix is: 000 000 000 Adding two matrices: 000 000 000