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