c语言程序设计题输入n个字符串再按降序输出
时间: 2023-05-30 13:04:36 浏览: 176
以下是一个示例程序,可以输入n个字符串,然后按照字符串的字典顺序降序输出:
```c
#include <stdio.h>
#include <string.h>
#define MAX_N 100
#define MAX_LEN 100
void sort_strings(char strings[][MAX_LEN], int n);
int main() {
char strings[MAX_N][MAX_LEN];
int n, i;
printf("请输入字符串的个数n:");
scanf("%d", &n);
printf("请输入%d个字符串:\n", n);
for (i = 0; i < n; i++) {
scanf("%s", strings[i]);
}
sort_strings(strings, n);
printf("按照字典顺序降序输出的结果为:\n");
for (i = 0; i < n; i++) {
printf("%s\n", strings[i]);
}
return 0;
}
void sort_strings(char strings[][MAX_LEN], int n) {
int i, j;
char temp[MAX_LEN];
for (i = 0; i < n; i++) {
for (j = i + 1; j < n; j++) {
if (strcmp(strings[i], strings[j]) < 0) {
strcpy(temp, strings[i]);
strcpy(strings[i], strings[j]);
strcpy(strings[j], temp);
}
}
}
}
```
这个程序定义了一个名为`sort_strings`的函数,用于对字符串数组进行排序。该函数使用了`strcmp`函数来比较两个字符串的大小,如果字符串`s1`小于字符串`s2`,则`strcmp(s1, s2)`返回一个负数;如果字符串`s1`等于字符串`s2`,则`strcmp(s1, s2)`返回0;如果字符串`s1`大于字符串`s2`,则`strcmp(s1, s2)`返回一个正数。因此,如果我们要按照字典顺序降序排列字符串数组`strings`,我们可以在`sort_strings`函数中使用如下的比较语句:
```c
if (strcmp(strings[i], strings[j]) < 0) {
// 字符串i小于字符串j,需要交换它们的位置
// ...
}
```
这个程序还使用了一个二维字符数组`strings`来存储输入的字符串,其中`strings[i]`表示第i个字符串。我们可以使用`scanf`函数来输入字符串,例如:
```c
scanf("%s", strings[i]);
```
注意,我们并没有限制输入的字符串的长度,因此需要使用一个足够大的数组来存储每个字符串。在这个程序中,我们假设每个字符串的长度不超过`MAX_LEN`个字符,每个字符串的个数不超过`MAX_N`个。如果需要输入更多的字符串,可以适当调整这两个宏定义的值。
阅读全文
相关推荐
![txt](https://img-home.csdnimg.cn/images/20241231045021.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.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)
![c](https://img-home.csdnimg.cn/images/20250102104920.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)