|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
/*编写程序用来找到一组单词中“最大”单词和“最小”单词。当用户输入单词后,程序根据字典的排序顺序决定排在最前面和最后面的单词。当用户输入了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个字母的单词的时候。*/
#include<stdio.h>
#include<string.h>
int main()
{
char smallest_word[20],largest_word[20];
char a[20];
loop:{
printf("Enter word:");
scanf("%s",a);
if(strcmp(smallest_word,a)>0)
{
strcpy(smallest_word,a);
}
if(strcmp(largest_word,a)<0)
{
strcpy(largest_word,a);
}}
if(strlen(a)!=4)
goto loop;
printf("smallest word:");
puts(smallest_word);
printf("largest word:");
puts(largest_word);
}
本帖最后由 jackz007 于 2020-12-30 23:28 编辑
最大的问题就是 goto loop 语句,这种语句在结构化编程中是添乱和起副作用的东西。
- #include<stdio.h>
- #include<string.h>
- int main(void)
- {
- char a[20] , smallest_word[20] , largest_word[20] ;
- int i , m ;
- for(i = m = 0 ; m != 4 ; i ++) {
- printf("Enter word : ") ;
- for(m = 0 ; (a[m] = getchar()) != '\n' && m < 19 ; m ++) ;
- a[m] = '\0' ;
- if(! i) {
- strcpy(smallest_word , a) ;
- strcpy(largest_word , a) ;
- } else {
- if(strcmp(a , largest_word) > 0) strcpy(largest_word , a) ;
- else if(strcmp(a , smallest_word) < 0) strcpy(smallest_word , a) ;
- }
- }
- printf("smallest word : %s\n" , smallest_word) ;
- printf(" largest word : %s\n" , largest_word) ;
- }
复制代码
|
|