鱼C论坛

 找回密码
 立即注册
查看: 4063|回复: 2

请教这题怎么解,各位鱼友们~~~~

[复制链接]
发表于 2012-12-11 16:15:52 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
  1. #include <stdio.h>int main(void){ char c; int count, word; int repeat, ri; scanf("%d", &repeat); getchar(); for(ri = 1; ri <= repeat; ri++){ c = getchar();/*---------*/ printf("count = %d\n", count); }}
复制代码

程序填空,不要改变与输入输出有关的语句。输入一个正整数repeat (0<repeat<10),做repeat次下列运算:输入一行字符,以回车结束,统计其中单词的个数。各单词之间用空格分隔,空格数可以是多个。输入输出示例:括号内是说明输入2   (repeat=2)Let's  go   to room  209.  Programming is fun输出count = 5     ("Let's  go   to room  209."中有5个单词)count = 3     ("  Programming is fun"中有3个单词)
小甲鱼最新课程 -> https://ilovefishc.com
发表于 2012-12-11 21:34:48 | 显示全部楼层
/*小弟不才,想出了这笨方法,不知道符合要求不。*/
#include <stdio.h>
int main(void)
{
        char c;
        int count=0, word;
        int repeat, ri;
        
        scanf("%d", &repeat);
        getchar();
        for(ri = 1; ri <= repeat; ri++)
        {
                c = getchar();
                count = 0;
                while (c!='\n')
                {
                        
                        if ( (c>='0')&&(c<='9') || (c>='a')&&(c<='z') || (c>='A')&&(c<='Z'))
                                word = 1;
                        if (c==' ' && word==1)   //当单词后面出现空格时,单词计数加1
                        {        
                                count ++;
                                word = 0;
                        }
                        c = getchar();
                        if ( (word==1) && (c=='\n'))  //单词后面直接跟回车时,单词计数加1
                                count ++;
                }
               
                        printf("count = %d\n", count);
        }
}


小甲鱼最新课程 -> https://ilovefishc.com
 楼主| 发表于 2012-12-12 13:37:37 | 显示全部楼层

谢谢,不过你的有点问题,第二个输入语句前有两个空格,这个问题没有考虑到。
这是我的做法
#include <stdio.h>
int main(void)
{
    char c;
    int count, word;
    int repeat, ri;
       
    scanf("%d", &repeat);
    getchar();
    for(ri = 1; ri <= repeat; ri++){
        c = getchar();
                if(c==' ')count=0;
                else if(c!=' ')count=1;
                while(c !='\n'){
                        while(c==' '){
                                for(word=0;c==' ';word++)
                     c = getchar();
                                count++;
                        }
                c = getchar();
                }

                printf("count = %d\n", count);
    }
        }
小甲鱼最新课程 -> https://ilovefishc.com
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-11-16 20:32

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表