含有五个元素的数组,输入六个数,前五个作为他的值,最后一个作为j,找出数组中和为j的两个数,同样的数字不能用两次
时间: 2024-03-09 17:48:59 浏览: 27
好的,以下是一个在 C++ 中实现的查找数组中和为 j 的两个数的程序,其中每个数字只能使用一次:
```c++
#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
int nums[5], j;
cout << "请输入五个数字,每个数字只能使用一次:\n";
for (int i = 0; i < 5; i++) {
cin >> nums[i];
}
cout << "请输入一个数字 j:\n";
cin >> j;
unordered_set<int> numSet;
bool found = false;
for (int i = 0; i < 5; i++) {
int complement = j - nums[i];
if (numSet.find(complement) != numSet.end()) {
cout << "数组中和为 " << j << " 的两个数为:" << nums[i] << " 和 " << complement << endl;
found = true;
break;
}
numSet.insert(nums[i]);
}
if (!found) {
cout << "数组中不存在和为 " << j << " 的两个数。" << endl;
}
return 0;
}
```
该程序将从用户处输入五个数字,并将它们存储在一个整数数组中。然后,用户还需要输入一个数字 j,程序将在数组中查找和为 j 的两个数字。程序使用 `unordered_set` 来存储已经出现过的数字,然后在遍历数组时,对于每个数字,计算它的补数(即 j - nums[i]),并在 `unordered_set` 中查找是否存在该补数。如果存在,则说明已经找到了和为 j 的两个数字。如果遍历完整个数组后仍没有找到和为 j 的两个数字,则说明数组中不存在这样的两个数字。