解题思路: 我们的想法是,定义变量分别存储数字,字母,空格和其他字符在字符串中出现的次数。当出现相应字符时,对应变量加一。 那么,我们就需要一个可以一个一个读入字符的函数,用来控制数据读入。每次计数都是一个重复的过程,那我们可以采用循环结构。
这里介绍一个函数,getchar()函数用来读入字符,当遇到回车时,结束读入过程。我们可以用while循环和此函数完成此题。具体代码如下:
注意事项:1.要注意while循环控制条件中 (c=getchar())最外层括号不可省略,具体可参考C语言运算符优先级参考表。
2.if选择结构中也可不采用ASC||码,可直接用对应字符作为判断条件
参考代码:
#include<stdio.h> int main() { int num=0,letter=0,space=0,other=0; int c; while((c=getchar())!='\n') { if(48<=c&&c<=57) num++; else if(65<=c&&c<=90||97<=c&&c<=122) letter++; else if(c==32) space++; else other++; } printf("%d %d %d %d",letter,num,space,other); return 0; }
0.0分
26 人评分
#include <stdio.h> int main(int argc, char const *argv[]) { int ch; int alphabets,numbers,blanks,others = 0; while((ch = getchar()) != '\n') { if(ch >= 65 && ch <= 90||ch >= 97 && ch <= 122) alphabets++; else if(ch >= 48 && ch <= 57) numbers++; else if(ch == 32 ) blanks++; else others++; } printf("%d %d %d %d", alphabets,numbers,blanks,others); return 0; } 为什么numbers的结果不对?
#include<stdio.h> int main() { int letter=0, number=0, blank=0, other=0,c; while ((c=getchar()) != '\n') { if (c >= 'a' && c <= 'z' or c >= 'A' && c <= 'Z') letter++; else if (c >= '0' && c <= '9') number++; else if (c == ' ') blank++; else other++; } printf("%d %d %d %d", letter, number, blank, other); }
#include<stdio.h> int main(){ char ch; int a=0,b=0,c=0,d=0; while( scanf("%c",&ch)!=EOF && ch!='\n' ){ if(ch==' '){ c++; }else if(ch>='0' &&ch<='9'){ b++; }else if( (ch>='a' && ch>='z') || (ch>='A' && ch>='Z')){ a++; }else{ d++; } } printf("%d %d %d %d\n",a,b,c,d); return 0; } 请问为啥这样就提交不过去
简单的a+b (C语言代码)浏览:335 |
printf基础练习2 (有点不明白)浏览:836 |
C语言程序设计教程(第三版)课后习题5.4 (C语言代码)浏览:1294 |
2003年秋浙江省计算机等级考试二级C 编程题(2) (C语言代码)浏览:581 |
a+b浏览:432 |
C语言程序设计教程(第三版)课后习题10.1 (C语言代码)浏览:560 |
C语言程序设计教程(第三版)课后习题5.5 (C语言代码)浏览:553 |
简单的a+b (C语言代码)浏览:543 |
蛇行矩阵 (C语言代码)浏览:498 |
母牛的故事 (C语言代码)浏览:478 |