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]);
}
}
}
}
}
}
}
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP