#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include<string.h> int main() { char a[100]; gets(a); int t; int len = strlen(a); int count[27] = { 0 }; char s[27] = { 0 }; int num[27] = { 0 }; for (int i = 1; i <= len; i++) { if (a[i] > 'a' && a[i] < 'z') { count[a[i] - 'a' + 1]++; } if (a[i] > 'A' && a[i] < 'Z') { count[a[i] - 'A' + 1]++; } } for (int j = 1, i = 1; i <= len; j++, i++) { num[j] = count[i]; } for (int j = 1; j < 26; j++) { for (int i = 1; i < 26 - i; i++) { if (count[i] < count[i + 1]) { t = count[i]; count[i] = count[i + 1]; count[i + 1] = t; } } } int max = count[1]; char c; int flag = 0; while (max >= 0) { for (int i = 1; i <= 26; i++) { if (num[i] == max) { c = i + 'A'; if (flag == 0) { printf("%c-%d", c, max); flag = 1; } else printf(" %c-%d", c, max); } } max--; } return 0; }这个代码怎么修改
时间: 2023-07-14 16:11:48 浏览: 87
duojikongzhi.rar_Unsigned_c++include <reg51>
这个代码有几个问题需要修改:
1. 使用 `gets()` 函数会存在安全隐患,应该改用 `fgets()` 函数。
2. 在 `for` 循环中,数组下标应该从0开始,而不是从1开始。
3. 最后的输出格式不够清晰,应该加上换行符。
下面是修改后的代码:
```c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
int main() {
char a[100];
fgets(a, 100, stdin);
int len = strlen(a);
int count[26] = { 0 };
int num[26] = { 0 };
for (int i = 0; i < len; i++) {
if (a[i] >= 'a' && a[i] <= 'z') {
count[a[i] - 'a']++;
}
if (a[i] >= 'A' && a[i] <= 'Z') {
count[a[i] - 'A']++;
}
}
for (int j = 0, i = 0; i < 26; j++, i++) {
num[j] = count[i];
}
for (int j = 0; j < 26; j++) {
for (int i = 0; i < 26 - i - 1; i++) {
if (count[i] < count[i + 1]) {
int t = count[i];
count[i] = count[i + 1];
count[i + 1] = t;
}
}
}
int max = count[0];
int flag = 0;
while (max >= 0) {
for (int i = 0; i < 26; i++) {
if (num[i] == max) {
char c = i + 'A';
if (flag == 0) {
printf("%c-%d", c, max);
flag = 1;
}
else {
printf(" %c-%d", c, max);
}
}
}
max--;
}
printf("\n");
return 0;
}
```
阅读全文