Problem K “最小”和“最大”单词

该博客介绍了编写程序找出一组单词中“最小”和“最大”单词的方法。程序根据字典顺序决定单词顺序,当输入4个字母的单词时停止读入。博客还给出了两种不同的C语言实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem Description
编写程序找出一组单词中“最小”单词和“最大”单词。输入单词后,程序根据字典顺序决定排在最前面和最后面的单词。当输入4个字母的单词时,程序停止读入。
假设所有的单词都不超过20个字母。
Input Description
每行输入一个单词。
Output Description
第一行输出“最小”单词。
第二行输出“最大”单词。
Sample Input
dog
zebra
rabbit
catfish
walrus
cat
fish
Sample Output
cat
zebra

答案:
1.
#include <stdio.h>
#include <string.h>

int main()
{
    int n;
    char a[20][20];
    char min[20], max[20];
    for(n = 0; ;n++)
    {
        scanf("%s", &a[n]);
        if(strlen(a[n]) == 4)
            break;
    }
    strcpy(min, a[0]);
    strcpy(max, a[0]);
    for(int i = 0; i < n; i++)
    {
        if(strcmp(a[i], min) < 0)
            strcpy(min, a[i]);
        if(strcmp(a[i], max) > 0)
            strcpy(max, a[i]);
    }
    printf("%s\n", min);
    printf("%s", max);

    return 0;
}


2.
#include<stdio.h>
#include<string.h>
int main(){
    int i;
    char p[20][10],smallest_word[10],largest_word[10];
    
    while(strlen(gets(p[i++]))!=4);//读入用户输入的单词存放在字符数组中,当输入四个字母的单词,停止读入
    for(i=0,strcpy(smallest_word,p[i]);;i++)
    {
        if(strcmp(p[i],smallest_word)<0)
            strcpy(smallest_word,p[i]);//寻找"最小"的单词,存放在数组smallest_word中
        if(strcmp(p[i],largest_word)>0)
            strcpy(largest_word,p[i]);//寻找"最大"的单词,存放在数组largest_word中
        if(strlen(p[i])==4)
            break;//当遇到四个字母的单词结束寻找
    }
    puts(smallest_word);
    puts(largest_word);
    return 0;
}

答案:
1.
#include <stdio.h>
#include <string.h>

int main()
{
    int n;
    char a[20][20];
    char min[20], max[20];
    for(n = 0; ;n++)
    {
        scanf("%s", &a[n]);
        if(strlen(a[n]) == 4)
            break;
    }
    strcpy(min, a[0]);
    strcpy(max, a[0]);
    for(int i = 0; i < n; i++)
    {
        if(strcmp(a[i], min) < 0)
            strcpy(min, a[i]);
        if(strcmp(a[i], max) > 0)
            strcpy(max, a[i]);
    }
	printf("%s\n", min);
	printf("%s", max);

    return 0;
}


2.
#include<stdio.h>
#include<string.h>
int main(){
	int i;
	char p[20][10],smallest_word[10],largest_word[10];
	
	while(strlen(gets(p[i++]))!=4);//读入用户输入的单词存放在字符数组中,当输入四个字母的单词,停止读入
	for(i=0,strcpy(smallest_word,p[i]);;i++)
    {
		if(strcmp(p[i],smallest_word)<0)
	        strcpy(smallest_word,p[i]);//寻找"最小"的单词,存放在数组smallest_word中
        if(strcmp(p[i],largest_word)>0)
	        strcpy(largest_word,p[i]);//寻找"最大"的单词,存放在数组largest_word中
		if(strlen(p[i])==4)
		    break;//当遇到四个字母的单词结束寻找
	}
	puts(smallest_word);
	puts(largest_word);
	return 0;
}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小木苓

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值