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
廣告