C语言降序排序整数并输出
时间: 2024-05-07 17:24:00 浏览: 17
Sure, 可以使用C语言中的qsort()函数来实现降序排序整数,代码如下:
```
#include <stdio.h>
#include <stdlib.h>
// 比较函数,用于qsort()函数中
int compare(const void* a, const void* b) {
// 转换为指针
const int* x = (const int*) a;
const int* y = (const int*) b;
// 返回y-x实现降序排序
return *y - *x;
}
int main() {
int nums[] = { 8, 2, 7, 5, 1, 9, 3, 6, 4 };
int n = sizeof(nums) / sizeof(nums[0]);
// 使用qsort()函数进行降序排序
qsort(nums, n, sizeof(int), compare);
// 输出排序后的结果
printf("Sorted array in descending order: ");
for (int i = 0; i < n; i++) {
printf("%d ", nums[i]);
}
return 0;
}
```
执行结果:
```
Sorted array in descending order: 9 8 7 6 5 4 3 2 1
```
相关问题
C语言输入整数并降序排序输出
好的,这个问题可以回答。以下是 C 代码实现:
```
#include <stdio.h>
#define MAX_NUMS 100
int main() {
int numbers[MAX_NUMS];
int num_count = 0;
printf("请输入一些整数(以-1结尾):\n");
// 读入数字,并记录它们的数量
int num = 0;
while (scanf("%d", &num) && num != -1) {
if (num_count < MAX_NUMS) {
numbers[num_count++] = num;
} else {
printf("数字超过了最大限制,只能处理前 %d 个。", MAX_NUMS);
break;
}
}
// 降序排序
for (int i = 0; i < num_count - 1; i++) {
for (int j = i + 1; j < num_count; j++) {
if (numbers[i] < numbers[j]) {
int tmp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = tmp;
}
}
}
// 输出结果
printf("排序结果为:\n");
for (int i = 0; i < num_count; i++) {
printf("%d ", numbers[i]);
}
printf("\n");
return 0;
}
```
用c语言输入10个整数,对这10个整数降序排序。
以下是使用冒泡排序法对10个整数进行降序排序的C语言代码:
```c
#include <stdio.h>
int main() {
int arr[10], temp;
// 读入10个整数
printf("输入10个整数:\n");
for (int i = 0; i < 10; i++) {
scanf("%d", &arr[i]);
}
// 冒泡排序,降序
for (int i = 0; i < 9; i++) {
for (int j = i + 1; j < 10; j++) {
if (arr[i] < arr[j]) {
// 交换两个数
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
// 输出排序结果
printf("降序排序后的结果:\n");
for (int i = 0; i < 10; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
```
输入示例:
```
输入10个整数:
1 3 2 5 4 7 6 9 8 10
```
输出示例:
```
降序排序后的结果:
10 9 8 7 6 5 4 3 2 1
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![text/plain](https://img-home.csdnimg.cn/images/20210720083646.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)