请用C++编写程序用来找到一组单词中“最大”的单词和“最小”的单词。

来源:百度知道 编辑:UC知道 时间:2024/06/18 14:04:40
编写程序用来找到一组单词中“最大”单词和“最小”单词。当用户输入单词后,程序根据字典的排序顺序决定排在最前面和最后面的单词。当用户输入了4个字母的单词时,程序必须停止读入。假设所有单词都不超过20个字母。程序与用户的交互显示如下所示:

Enter word: dog

Enter word: zebra

Enter word: rabbit

Enter word: catfish

Enter word: walrus

Enter word: cat

Enter word: fish

Smallest word: cat

Largest word: zebra

提示:使用两个名为smallest_word和largest_word的字符串来记录当前输入的“最小”单词和“最大”单词。每次用户输入新单词,就用strcmp函数把它与smallest_word进行比较。如果新的单词比smallest_word“小”,就用strcpy函数把新单词保存到smallest_word中。用类似的方式与larges_word也进行比较。用strlen函数来判断用户输入4个字母的单词的时候。
20个字母是在假设的情况下,而要编写的程序是要不超个4个字母的

//你的题目好像有问题,最长的应该是catfish吧,还有最后一个是不是不要判断的(4个字母的)
//程序如下:
#include <stdio.h>
#include <string.h>
int main()
{
char smallest_word[20]="",largest_word[20]="",input[20];
int number=0;
while(1)
{
printf("Enter word: ");
scanf("%s",input);
number=strlen(input);
if(number==4)
break;
if(strlen(smallest_word)==0&&strlen(largest_word)==0)
{
strcpy(largest_word,input);
strcpy(smallest_word,input);
}
else
{
if(number>strlen(largest_word)) strcpy(largest_word,input);
if(number<strlen(smallest_word)) strcpy(smallest_word,input);
}
}
printf("Smallest word: %s\n",smallest_word);
printf("Largest word: %s\n",largest_word);
return 0;
}

你又说不能超过4个字母,又说最多20个字母,到底什么意思?