首先是我们肯定不能忘记的环节
主函数的main一定不要打成mian哦
#include<stdio.h>
int main()
{
}
我们要统计的字符类型有英文字符(letter)、空格和回车(blank)、数字(digit)和其他字符(other)。所以我们用int定义这四个变量并且初始化为0,并且我们要使用for循环,所以再定义一个i用来计数(i暂时不需要初始化)。
int letter,blank,digit,other,i;//定义这五个变量
letter=blank=digit=other=0; //初始化变量
由于我们需要接受从键盘输入的字符数据,所以我们再定义一个字符型的变量
char ch; //定义一个变量名为ch的字符型变量
接下来就要使用我们的for循环了,for循环后面不要打 ; 很多人都会犯这个错误
for(i=1;i<=10;i++) //i=1 当i小于等于10时i++ 再执行循环体内的语句
{
}
再把我们循环体内的代码补全
ch=getchar(); //从键盘上接受字符
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')) //当接收字符为大小写字母时,letter+1
{
letter++;
}else if (ch == ' ' || ch == '\n') //当接收字符为空格回车时,blank+1
{
blank++;
}else if(ch>='0'&& ch<='9') //当接受字符为数字时,digit+1
{
digit++;
}else{
other++; //为其他字符就other+1
}
以上循环会进行十次,循环从键盘接收字符再判断赋值这个过程
让我们用printf语句将结果输出
printf("letter = %d, blank = %d, digit = %d, other = %d",letter,blank,digit,other);
所有代码结合在一块我们的程序就完成了
#include<stdio.h>
int main()
{
int letter,blank,digit,other,i;
letter=blank=digit=other=0;
char ch;
for(i=1;i<=10;i++)
{
ch=getchar();
if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))
{
letter++;
}else if (ch == ' ' || ch == '\n') // (ch=(' '||'\n'))
{
blank++;
}else if(ch>='0'&& ch<='9')
{
digit++;
}else{
other++;
}
}
printf("letter = %d, blank = %d, digit = %d, other = %d",letter,blank,digit,other);
return 0;
}
这题只要掌握了逻辑运算符和for循环的使用就可以轻松解决哦!