用于计数数字和空格的c程序, [英] A c progarm for count digits and white space,

查看:75
本文介绍了用于计数数字和空格的c程序,的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我只是将一些C代码放入MS c ++ 6.0中运行,但是该代码不起作用.
无法输出期望结果.有人可以帮忙吗?谢谢:-


Hi,

I just put some c code into MS c++ 6.0 to run, but the code is not work.
It can''t output the expectation result. anyone can help? thanks:-


#include <stdio.h>

main()
{
    int c, i, nwhite, nother;
    int ndigit [ 10 ];

    nwhite = nother = 0;
    for( i = 0; i<10; ++i)
        ndigit [ i ] = 0;

    while (( c = getchar() ) != EOF)
        if( c >= ' 0 ' && c <= ' 9 ')
            ++ndigit [ c - ' 0 ' ];
        else if ( c == ' ' || c == ' \n ' || c == ' \t ')
            ++nwhite;
        else
            ++nother;

    printf(" digits = ");
    for ( i = 0 ; i <10; ++i )
        printf (" %d ", ndigit[ i ]);

    printf (", white space = %d , other = %d \n", nwhite, nother);
}



[edit]已添加代码块-OriginalGriff [/edit]



[edit]Code block added - OriginalGriff[/edit]

推荐答案

这是因为您要查找'' 0 ''而不是''0''.换句话说,除去空格字符以外的所有内容的填充.
It''s because you''re looking for '' 0 '' instead of ''0''. In other words, remove the padding for everything except the space character.


首先要注意的是,您需要摆脱比较文字中的虚假空格.
目前,比较是针对整个值"space zero space"而不是"zero".
试试:
The first thing to note is that you need to get rid of the spurious spaces in your comparison literals.
at the moment, the comparison is against teh whole value "space zero space" rather than "zero".
Try:
int c, i, nwhite, nother;
int ndigit [ 10 ];

nwhite = nother = 0;
for( i = 0; i<10; ++i)
{
    ndigit [ i ] = 0;
}
while (( c = getchar() ) != EOF)
{
    if( c >= '0' && c <= '9')
    {
        ++ndigit [ c - '0' ];
    }
    else if ( c == ' ' || c == '\n' || c == '\t')
        {
            ++nwhite;
    }
    else
    {
        ++nother;
    }
}
printf(" digits = ");
for ( i = 0 ; i <10; ++i )
{
    printf (" %d ", ndigit[ i ]);
}
printf (", white space = %d , other = %d \n", nwhite, nother);
c = getchar();

请注意,即使没有必要,我也会在每个语句周围添加块开始和结尾.这样做是值得的,尤其是在刚开始时,因为缩进很容易使您感到困惑,以为循环比实际更进一步:

Note that I have included block start and end around every statement, even when they aren''t necessary. It is worth doing this, particularly when you are just starting, as you can easily be confused by indentation into thinking a loop goes further than it actually does:

while (c != EOF)
   printf(".");
   c = getchar();

看起来很有效,但

Looks like it works, but

while (c != EOF)
{
   printf(".");
   c = getchar();
}

实际上是!


这篇关于用于计数数字和空格的c程序,的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆