以下是一个用 C 语言实现的英文单词统计助手的示例代码: ```c #include <stdio.h> #include <string.h> #include <ctype.h> #define MAX_LINE_LENGTH 1000 #define MAX_WORD_LENGTH 50 // 统计单词数量 int countWords(char text[]) { int wordCount = 0; int inWord = 0; for (int i = 0; text[i]!= '\0'; i++) { if (isalpha(text[i])) { if (!inWord) { wordCount++; inWord = 1; } } else { inWord = 0; } } return wordCount; } // 统计字符出现次数 void countCharacters(char text[], int charCount[]) { for (int i = 0; text[i]!= '\0'; i++) { if (isalpha(text[i])) { charCount[tolower(text[i]) - 'a']++; } } } // 交换函数用于排序 void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp; } // 冒泡排序 void bubbleSort(int arr[], char letters[], int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] < arr[j + 1]) { swap(&arr[j], &arr[j + 1]); swap(&letters[j], &letters[j + 1]); } } } } int main() { char text[MAX_LINE_LENGTH]; printf("请输入英文短文:\n"); fgets(text, MAX_LINE_LENGTH, stdin); int wordCount = countWords(text); printf("单词总数:%d\n", wordCount); int charCount[26] = {0}; countCharacters(text, charCount); char letters[26]; for (int i = 0; i < 26; i++) { letters[i] = 'a' + i; } bubbleSort(charCount, letters, 26); printf("字符出现次数(降序):\n"); for (int i = 0; i < 26; i++) { if (charCount[i] > 0) { printf("%c: %d\n", letters[i], charCount[i]); } } return 0; } ``` 以下是三个可行的改进建议: 1. 增加对输入内容的合法性检查,例如检查输入是否全为英文字符。 2. 优化排序算法,例如使用快速排序替代冒泡排序提高效率。 3. 将各个功能模块封装成单独的函数,提高代码的可维护性和可读性。 [2024-12-26 15:39:43 | AI写代码神器 | 691点数解答]