读书人

一个关于字符数统计的小程序,该怎么处

发布时间: 2013-07-09 09:50:48 作者: rapoo

一个关于字符数统计的小程序
用来统计各个数字及空白符以及其他字符出现次数的程序,请教错在那里了?
#include<stdio.h>
void main()
{
int i,c,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("digit=");
for(i=0;i<10;i++)
{
printf("%d",i);
printf("\t%d\n",ndigit[i]);
}
printf("nwhite=%d\nnother=%d\n",nwhite,nother);
}

}
C
[解决办法]

#include<stdio.h>
void main()
{
int i,c,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("digit=");
for(i=0;i<10;i++)
{
printf("%d",i);
printf("\t%d\n",ndigit[i]);
}
printf("nwhite=%d\nnother=%d\n",nwhite,nother);
}

}

[解决办法]
1 if(c >='0'&& c <= '9') // 应该是字符'9'

2 else if(c == ' '
[解决办法]
c == '\n'
[解决办法]
c == '\t') // 应该是 ==

2 ++ndigit[c-'0']; // 应该是减去字符'0',而不是值0


[解决办法]
#include <stdio.h>
#define MAX 1024
void main()
{
int ndigit[10] = {};
int number = 0;
int nwhite = 0;
int other = 0;
int i = 0;
char str[MAX];
char *p;
printf("please input a string:");
gets(str);
p = str;
while(*p != '\0')
{
if(*p >= '0' && *p <= '9')
ndigit[*p-'0']++;
else if(*p == ' ')
nwhite++;
else
other++;
p++;
}
printf("digit:\n");
for(i = 0; i < 10; i++)
{
printf("%d-----%d\n", i, ndigit[i]);
}
printf("nwhite=%d\nother=%d\n", nwhite, other);
}

你的程序问题比较多,我按照你的思路写了一个程序,应该能看懂,不懂再交流!Thanks!
[解决办法]


#include<stdio.h>
void main()
{
int i,c,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("digit=");
for(i=0;i<10;i++)
{
printf("%d",i);
printf("\t%d\n",ndigit[i]);
}
printf("nwhite=%d\nnother=%d\n",nwhite,nother);
}

[解决办法]
这一句就算修改了,难道不会造成数组越界吗????
++ndigit[c-'0'];


计数的话,用一个计数器不就ok了,难道这里有玄机????

读书人网 >C语言

热点推荐