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]); } } } } } } }
广告