C语言输入四个整数,要求将他们按从小到大的顺序输出
时间: 2023-05-25 20:03:16 浏览: 32
以下是一种简单的解法:
```c
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
// 冒泡排序
int arr[4] = {a, b, c, d};
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3 - i; j++) {
if (arr[j] > arr[j + 1]) {
swap(&arr[j], &arr[j + 1]);
}
}
}
// 输出结果
for (int i = 0; i < 4; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
注:上述代码使用了冒泡排序算法,时间复杂度为 O(n^2),当数据量较大时效率不高,更高效的排序算法可参考其他资料。
相关问题
c语言输入4个整数,按从小到大的顺序输出
以下是使用C语言编写的输入4个整数,按从小到大的顺序输出的代码:
```c
#include <stdio.h>
int main() {
int a, b, c, d;
printf("请输入四个整数:\n");
scanf("%d%d%d%d", &a, &b, &c, &d);
if (a > b) {
int tmp = a;
a = b;
b = tmp;
}
if (a > c) {
int tmp = a;
a = c;
c = tmp;
}
if (a > d) {
int tmp = a;
a = d;
d = tmp;
}
if (b > c) {
int tmp = b;
b = c;
c = tmp;
}
if (b > d) {
int tmp = b;
b = d;
d = tmp;
}
if (c > d) {
int tmp = c;
c = d;
d = tmp;
}
printf("从小到大排序后的结果为:%d %d %d %d\n", a, b, c, d);
return 0;
}
```
运行程序后,会要求用户输入四个整数,然后按从小到大的顺序输出这四个整数。程序中使用了多个 if 语句和中间变量来实现排序。
用c语言输入4个整数,要求按由小到大的顺序输出。
以下是C语言代码:
```c
#include <stdio.h>
int main() {
int num1, num2, num3, num4;
int temp;
printf("请输入四个整数:\n");
scanf("%d%d%d%d", &num1, &num2, &num3, &num4);
// 从小到大排序
if (num1 > num2) {
temp = num1;
num1 = num2;
num2 = temp;
}
if (num1 > num3) {
temp = num1;
num1 = num3;
num3 = temp;
}
if (num1 > num4) {
temp = num1;
num1 = num4;
num4 = temp;
}
if (num2 > num3) {
temp = num2;
num2 = num3;
num3 = temp;
}
if (num2 > num4) {
temp = num2;
num2 = num4;
num4 = temp;
}
if (num3 > num4) {
temp = num3;
num3 = num4;
num4 = temp;
}
// 输出排序后的结果
printf("从小到大排序后的结果为:%d %d %d %d\n", num1, num2, num3, num4);
return 0;
}
```
运行程序后,输入四个整数,程序将按照从小到大的顺序输出这四个数。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)