比较四个整数C语言代码
时间: 2023-09-17 22:10:16 浏览: 28
以下是比较四个整数的C语言代码:
1. 使用if语句进行逐一比较:
```c
#include <stdio.h>
int main() {
int a, b, c, d;
printf("Enter four integers: ");
scanf("%d %d %d %d", &a, &b, &c, &d);
if (a > b && a > c && a > d) {
printf("%d is the largest.\n", a);
} else if (b > a && b > c && b > d) {
printf("%d is the largest.\n", b);
} else if (c > a && c > b && c > d) {
printf("%d is the largest.\n", c);
} else {
printf("%d is the largest.\n", d);
}
return 0;
}
```
2. 使用数组存储四个数,然后使用循环找到最大值:
```c
#include <stdio.h>
int main() {
int nums[4];
printf("Enter four integers: ");
scanf("%d %d %d %d", &nums[0], &nums[1], &nums[2], &nums[3]);
int max = nums[0];
for (int i = 1; i < 4; i++) {
if (nums[i] > max) {
max = nums[i];
}
}
printf("%d is the largest.\n", max);
return 0;
}
```
3. 使用三目运算符逐一比较:
```c
#include <stdio.h>
int main() {
int a, b, c, d;
printf("Enter four integers: ");
scanf("%d %d %d %d", &a, &b, &c, &d);
int max = (a > b) ? a : b;
max = (max > c) ? max : c;
max = (max > d) ? max : d;
printf("%d is the largest.\n", max);
return 0;
}
```
4. 使用函数实现:
```c
#include <stdio.h>
int max(int a, int b) {
return (a > b) ? a : b;
}
int main() {
int a, b, c, d;
printf("Enter four integers: ");
scanf("%d %d %d %d", &a, &b, &c, &d);
int m1 = max(a, b);
int m2 = max(c, d);
int max_num = max(m1, m2);
printf("%d is the largest.\n", max_num);
return 0;
}
```
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)