返回列表 發帖

C# 7 306 矩陣相加

本帖最後由 李泳霖 於 2024-2-6 12:05 編輯

TQC+ 物件導向程式語言
最新一次更新時間:2024-01-05 14:51:04

1. 題目說明:
請新增一個主控台應用程式,加入C:\ANS.CSF\CS03資料夾中的CSD03.cs進行編寫。依下列題意進行作答:建立兩個二維陣列,予以加總後輸出,使輸出值符合題意要求。檔案名稱請另存新檔為CSA03.cs,儲存於C:\ANS.CSF\CS03資料夾,再進行評分。
  1.         static int[,] a = { { 1, 2, 3 }, { 4, 5, 6 } };
  2.         static int[,] b = new int[2, 3];
複製代碼
2. 設計說明:
Main()方法中已宣告兩個二維陣列a、b,其中b陣列內容需由使用者輸入六個1-100之間的正整數,並且以半形空格隔開。
將a、b陣列傳遞給程式中已定義的compute()方法,在compute()方法中將二維陣列a、b加總,再傳遞給print()方法將其加總結果輸出,以陣列一維為一列輸出,共輸出兩列。
每個數字固定為四位數且靠右對齊,若輸入有誤,請輸出【error】。

3. 輸入輸出:
輸入說明
六個1-100之間的正整數,以半形空格隔開

輸出說明
二維陣列加總

範例輸入1
9 8 7 6 5 4
範例輸出1
  10  10  10
  10  10  10

範例輸入2
11 23
範例輸出2
error

4. 評分項目:
(1) 符合設計說明輸出正確格式配分        20
  1. using ConsoleApp1;
  2. using System;//程式庫呼叫
  3. using System.ComponentModel.DataAnnotations;
  4. using System.Linq.Expressions;
  5. using ABC.qq;


  6. class Program//負責一部分工作的人
  7. {
  8.     static int[,] a = { { 1, 2, 3 }, { 4, 5, 6 } };
  9.     static int[,] b = new int[2, 3];
  10.     static void Main()
  11.     {

  12.         try
  13.         {
  14.             string[] str = Console.ReadLine().Split(' ');
  15.             if (str.Length != 6)
  16.                 throw new Exception();
  17.             for (int i = 0; i < str.Length; i++)
  18.             {
  19.                 if (Convert.ToInt32(str[i]) < 1 || Convert.ToInt32(str[i]) > 100)
  20.                     throw new Exception();
  21.                 else
  22.                 {
  23.                     b[i <= 2 ? 0 : 1, i > 2 ? i - 3 : i] = Convert.ToInt32(str[i]);
  24.                 }
  25.             }
  26.             int[,] c = compute();
  27.             print(c);

  28.         }
  29.         catch
  30.         {
  31.             Console.WriteLine("error");
  32.         }
  33.         Console.ReadKey();
  34.     }
  35.     static int[,] compute()
  36.     {
  37.         try
  38.         {
  39.             int[,] c = new int[2, 3];
  40.             for (int i = 0; i < 2; i++)
  41.             {
  42.                 for (int j = 0; j < 3; j++)
  43.                 {
  44.                     c[i, j] = a[i, j] + b[i, j];
  45.                 }
  46.             }
  47.             return c;

  48.         }
  49.         catch
  50.         {
  51.             return null;
  52.         }
  53.     }
  54.     static void print(int[,] c)
  55.     {
  56.         for (int i = 0; i < 2; i++)
  57.         {
  58.             for (int j = 0; j < 3; j++)
  59.             {
  60.                 Console.Write(c[i, j].ToString().PadLeft(4));//此字串會以空格填補左側至指定的總長度


  61.             }
  62.             Console.WriteLine();
  63.         }

  64.     }
  65. }
複製代碼
istak.teach2@gmail.com

此帖僅作者可見

TOP

返回列表