编写一个能寻找指定和的整数对的C语言程序。输入 n ( n<= 100,000)个整数,找出其中的两个数,它们之和等于整数 m (假定肯定有解)。整数由键盘输入
时间: 2024-02-06 11:10:42 浏览: 99
以下是能寻找指定和的整数对的C语言程序:
```c
#include <stdio.h>
int main() {
int n, m, i, j;
int nums[100000];
printf("请输入整数个数n:");
scanf("%d", &n);
printf("请输入%d个整数:", n);
for (i = 0; i < n; i++) {
scanf("%d", &nums[i]);
}
printf("请输入要寻找的整数对的和m:");
scanf("%d", &m);
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (nums[i] + nums[j] == m) {
printf("找到了一组解:%d + %d = %d\n", nums[i], nums[j], m);
return 0;
}
}
}
return 0;
}
```
该程序中,首先读入整数个数n和n个整数,然后读入要寻找的整数对的和m。接着使用两重循环遍历所有可能的整数对,如果找到一组和为m的整数对,就输出解并结束程序。由于假定有解,因此程序不需要处理找不到解的情况。
相关问题
编写一个能寻找指定和的整数对的C语言程序。输入 n ( n<= 100,000)个整数,找出其中的两个数,它们之和等于整数 m (假定肯定有解)。
以下是一个简单的 C 语言程序,用于寻找指定和的整数对:
```c
#include <stdio.h>
int main() {
int n, m;
scanf("%d%d", &n, &m);
int nums[n];
for (int i = 0; i < n; i++) {
scanf("%d", &nums[i]);
}
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (nums[i] + nums[j] == m) {
printf("%d %d\n", nums[i], nums[j]);
return 0;
}
}
}
return 0;
}
```
首先,程序从标准输入中读取两个整数 `n` 和 `m`,分别代表整数个数和目标和。然后,程序定义一个整数数组 `nums`,用于存储输入的 n 个整数。
接下来,程序使用两个嵌套的循环遍历数组中的所有整数对,检查它们的和是否等于目标和。如果找到了这样的一对整数,程序就输出它们并结束运行。
注意,这个程序假定肯定有解。如果不存在这样的一对整数,程序可能会陷入无限循环。
编写一个能寻找指定和的整数对的C语言程序。输入 n ( n<= 100,000)个整数,找出其中的两个数,它们之和等于整数 m (假定肯定有解)。
以下是一个简单的C语言程序,可以寻找指定和的整数对:
```c
#include <stdio.h>
#define MAXN 100000
int a[MAXN];
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if (a[i] + a[j] == m) {
printf("%d %d\n", a[i], a[j]);
return 0;
}
}
}
return 0;
}
```
程序首先读取输入的整数个数 n 和指定和 m,然后读入 n 个整数。接下来,程序使用两个 for 循环来遍历所有可能的整数对,如果找到了符合条件的整数对,则输出它们并返回 0。如果程序执行到了最后一行,说明必定会找到符合条件的整数对,因此不需要再加判断条件。
需要注意的是,此程序假设输入的整数对应的数组中,每个元素都不相同。如果有多个元素相同,可以在读入时将它们去重,或者在查找时加上一些条件判断语句。
阅读全文
相关推荐
















