C# 程式用於確定陣列中是否有兩個整數與給定整數相加


以下為我們的陣列 −

int[] arr = new int[] {
   7,
   4,
   6,
   2
};

假設給定的整數應等於其他兩個整數之和 −

int res = 8;

用於獲得和並檢驗相等性。

for (int i = 0; i < arr.Length; i++) {
   for (int j = 0; j < arr.Length; j++) {
      if (i != j) {
         int sum = arr[i] + arr[j];
         if (sum == res) {
            Console.WriteLine(arr[i]);
         }
      }
   }
}

示例

using System;
using System.Collections.Generic;

namespace Demo {
   public class Program {
      public static void Main(string[] args) {
         int[] arr = new int[] {
            7,
            4,
            6,
            2
         };
         // given integer
         int res = 8;
         Console.WriteLine("Given Integer {0}: ", res);
         Console.WriteLine("Sum of:");
         for (int i = 0; i < arr.Length; i++) {
            for (int j = 0; j < arr.Length; j++) {
               if (i != j) {
                  int sum = arr[i] + arr[j];
                  if (sum == res) {
                     Console.WriteLine(arr[i]);
                  }
               }
            }
         }
      }
   }
}

更新日期:22-06-2020

850 次

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.