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]; // setting matrix row and columns size n = 3; Console.Write("Enter elements in the first matrix:
"); 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:
"); for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { arr2[i, j] = Convert.ToInt32(Console.ReadLine()); } } Console.Write("
First matrix is:
"); for (i = 0; i < n; i++) { Console.Write("
"); for (j = 0; j < n; j++) Console.Write("{0}\t", arr1[i, j]); } Console.Write("
Second matrix is:
"); for (i = 0; i < n; i++) { Console.Write("
"); 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("
Adding two matrices:
"); for (i = 0; i < n; i++) { Console.Write("
"); for (j = 0; j < n; j++) Console.Write("{0}\t", arr3[i, j]); } Console.Write("
"); } }
输出
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
广告