c - 寻找最小和最大单词的程序

标签 c string

这是来自 K.N. King book 在一系列单词中找到最小和最大的单词,并在单词长度为 4 时停止。但它不能正常工作。

#include <stdio.h>
#include <string.h>

#define N 20


int main(void) {
    char smallest_word[N];
    char largest_word[N];
    char current_word[N];
    printf("Enter word: ");
    gets(current_word);
    strcpy(smallest_word, strcpy(largest_word, current_word));
    while(strlen(current_word) != 4){
        printf("Enter word: ");
        gets(current_word);
        if(strcmp(current_word, smallest_word) < 0)
            strcpy(smallest_word, current_word);
        if(strcmp(current_word, largest_word) > 0)
            strcpy(largest_word, current_word);

    } 
    printf("\nSmallest word: %s\n", smallest_word);
    printf("Largest word: %s\n", largest_word);
    return 0;
}

假设我输入:

cat 
dog 
catfish
bear

给予

Output:
Smallest Word: bear
Largest Word: dog

我认为这是错误的。

最佳答案

如果我们把lexicographic order中的四个字排列起来,我们得到:

  • 鲶鱼

因此输出看起来是正确的(“bear”是第一个,“dog”是最后一个)。

关于c - 寻找最小和最大单词的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15336054/

相关文章:

c - fscanf 不读取包含星号字符的文件

python - 找到具有 k 个唯一字母的最大可能子串。 (递归)

c# - 如果存在超过 37 个字符,如何将字符串拆分为多行

c - 如何根据传感器读数动态打印字符串

Swift:比较字符串的第一个字符

C 数组值因 printf 语句而改变?

c - 将文本文件读取到二维数组时出现段错误

c++ - 读取控制台调色板的 RGB 值

c - Linux内核模块开发buildroot

python - Pandas 替换(删除)字符串中的不同字符