C语言编写两个函数,其功能分别为: ⑴ 求N个整数的次大值和次小值 ⑵ 求两个整数的最大公约数和最小公倍数
时间: 2024-05-16 21:15:11 浏览: 9
⑴ 求N个整数的次大值和次小值
```c
#include <stdio.h>
void find_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];
}
}
}
int main() {
int arr[] = {3, 7, 1, 9, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int second_largest, second_smallest;
find_second_largest_smallest(arr, n, &second_largest, &second_smallest);
printf("Second largest element: %d\n", second_largest);
printf("Second smallest element: %d\n", second_smallest);
return 0;
}
```
⑵ 求两个整数的最大公约数和最小公倍数
```c
#include <stdio.h>
int gcd(int a, int b) {
if (a == 0) {
return b;
}
return gcd(b % a, a);
}
int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
int main() {
int a = 18, b = 24;
printf("GCD of %d and %d is %d\n", a, b, gcd(a, b));
printf("LCM of %d and %d is %d\n", a, b, lcm(a, b));
return 0;
}
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)