用C语言完成:用while循环从键盘用数组随机读入N个字符(大小写混输),直到遇到回车为止。对读入的字符用选择法按从大到小的顺序重新排列输出。
时间: 2023-05-26 13:01:57 浏览: 71
```
#include <stdio.h>
int main() {
char arr[100];
int size = 0;
while (1) {
char c = getchar();
if (c == '\n') break;
arr[size++] = c;
}
for (int i = 0; i < size - 1; i++) {
int maxIndex = i;
for (int j = i + 1; j < size; j++) {
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}
char temp = arr[i];
arr[i] = arr[maxIndex];
arr[maxIndex] = temp;
}
for (int i = 0; i < size; i++) {
printf("%c ", arr[i]);
}
printf("\n");
return 0;
}
```
相关问题
用C语言编写:编写一个函数sort,使用指针的方法对一个数组a[10],实现从大到小的排序。
好的,以下是代码实现:
```c
void sort(int *a, int n) {
int i, j, temp;
for (i = 0; i < n-1; i++) {
for (j = i+1; j < n; j++) {
if (*(a + i) < *(a + j)) {
temp = *(a + i);
*(a + i) = *(a + j);
*(a + j) = temp;
}
}
}
}
```
其中,`a` 是一个指向数组首元素的指针,`n` 表示数组的元素个数。函数中使用双重循环遍历数组元素,如果前一个元素的值小于后一个元素的值,则交换它们的位置。这样,最终就能得到一个从大到小排序的数组。
用c语言写从键盘输入一个字符串,用冒泡法对该字符串中的字符由大到小进行排序,并输出结果。
好的,下面是用C语言实现字符串冒泡排序的代码:
```c
#include <stdio.h>
#include <string.h>
int main() {
char str[100];
printf("请输入一个字符串:");
scanf("%s", str);
int len = strlen(str);
for(int i=0; i<len-1; i++) {
for(int j=0; j<len-i-1; j++) {
if(str[j] < str[j+1]) {
char temp = str[j];
str[j] = str[j+1];
str[j+1] = temp;
}
}
}
printf("排序后的字符串为:%s\n", str);
return 0;
}
```
这段代码首先读入一个字符串,然后获取该字符串的长度。接着,使用冒泡排序对字符串中的字符进行排序,最后输出排序后的字符串。注意,这里使用字符数组来保存字符串,因为字符串本质上就是一个字符数组。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![text/x-c](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/pdf](https://img-home.csdnimg.cn/images/20210720083512.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)