编写两个函数,其功能分别为: ①求N个整数的次大值和次小值。 ②求两个整数的最大公约数和最小公倍数。 输人10个整数,调用函数求它们的次大值和次小值,及次大值和次小值的最大公约数和最小公倍数。 要求:这两个函数和主函数分属3个文件。
时间: 2024-05-16 20:17:34 浏览: 105
调用函数求两个数的最大公约数和最小公倍数(C语言练习例程)
5星 · 资源好评率100%
函数1:求N个整数的次大值和次小值
```c
// second_largest_smallest.c
#include <stdio.h>
void second_largest_smallest(int arr[], int n, int *second_largest, int *second_smallest) {
int largest = arr[0], smallest = arr[0];
*second_largest = arr[0], *second_smallest = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > largest) {
*second_largest = largest;
largest = arr[i];
} else if (arr[i] > *second_largest && arr[i] != largest) {
*second_largest = arr[i];
}
if (arr[i] < smallest) {
*second_smallest = smallest;
smallest = arr[i];
} else if (arr[i] < *second_smallest && arr[i] != smallest) {
*second_smallest = arr[i];
}
}
}
```
函数2:求两个整数的最大公约数和最小公倍数
```c
// gcd_lcm.c
#include <stdio.h>
int get_gcd(int a, int b) {
while (a != b) {
if (a > b) {
a -= b;
} else {
b -= a;
}
}
return a;
}
int get_lcm(int a, int b) {
return a * b / get_gcd(a, b);
}
```
主函数
```c
// main.c
#include <stdio.h>
#include "second_largest_smallest.h"
#include "gcd_lcm.h"
#define N 10
int main() {
int arr[N], second_largest, second_smallest, gcd, lcm;
printf("Enter %d integers: ", N);
for (int i = 0; i < N; i++) {
scanf("%d", &arr[i]);
}
second_largest_smallest(arr, N, &second_largest, &second_smallest);
gcd = get_gcd(second_largest, second_smallest);
lcm = get_lcm(second_largest, second_smallest);
printf("Second largest: %d\n", second_largest);
printf("Second smallest: %d\n", second_smallest);
printf("GCD: %d\n", gcd);
printf("LCM: %d\n", lcm);
return 0;
}
```
头文件1:second_largest_smallest.h
```c
// second_largest_smallest.h
void second_largest_smallest(int arr[], int n, int *second_largest, int *second_smallest);
```
头文件2:gcd_lcm.h
```c
// gcd_lcm.h
int get_gcd(int a, int b);
int get_lcm(int a, int b);
```
编译和运行
```shell
$ gcc -o main main.c second_largest_smallest.c gcd_lcm.c
$ ./main
Enter 10 integers: 1 2 3 4 5 6 7 8 9 10
Second largest: 9
Second smallest: 2
GCD: 1
LCM: 18
```
阅读全文