C语言对四个数按从大到小排序
时间: 2023-11-26 19:05:50 浏览: 128
好的,我可以帮您解决这个问题,以下是将四个数按从大到小排序的C语言代码示例:
```
#include <stdio.h>
void sort(int *arr, int n);
int main() {
int arr[4], i;
printf("请输入四个需要排序的数:\n");
for (i = 0; i < 4; i++) {
scanf("%d", &arr[i]);
}
sort(arr, 4);
printf("排序后的结果为:\n");
for (i = 0; i < 4; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
void sort(int *arr, int n) {
int i, j, tmp;
for (i = 0; i < n - 1; i++) {
for (j = i + 1; j < n; j++) {
if (arr[j] > arr[i]) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
}
}
```
以上是将四个数按从大到小排序的C语言代码示例,希望能对您有所帮助。
相关问题
C语言对四个数按从大到小排序,不用冒泡排序
可以使用选择排序来实现。代码如下:
```c
#include <stdio.h>
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
void sort(int arr[], int n) {
int i, j, max_idx;
for (i = 0; i < n - 1; i++) {
max_idx = i;
for (j = i + 1; j < n; j++) {
if (arr[j] > arr[max_idx]) {
max_idx = j;
}
}
swap(&arr[i], &arr[max_idx]);
}
}
int main() {
int arr[] = {5, 8, 1, 3};
int n = sizeof(arr) / sizeof(arr[0]);
sort(arr, n);
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
输出结果为:8 5 3 1
c语言四个数大小排序
好的,以下是C语言实现四个数大小排序的代码示例:
```
#include <stdio.h>
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a, b, c, d;
printf("请输入四个整数:");
scanf("%d %d %d %d", &a, &b, &c, &d);
if (a > b) swap(&a, &b);
if (a > c) swap(&a, &c);
if (a > d) swap(&a, &d);
if (b > c) swap(&b, &c);
if (b > d) swap(&b, &d);
if (c > d) swap(&c, &d);
printf("排序后的顺序为:%d %d %d %d\n", a, b, c, d);
return 0;
}
```
我们定义了一个 `swap` 函数来交换两个数的值,然后在主函数中通过多次比较和调用 `swap` 函数来实现四个数的排序。最后输出排序后的结果。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.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)