从键盘输入任意的字符,按下列规则进行分类计数。 第一类:‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’ 第二类:‘+’, ‘-’, ‘*’, ‘/’, ‘%’, ‘=’ 第三类:其它字符。 **输入要求:用getchar()输入字符,以\标志输入的结束(\也需要统计,统计到第三类中) **输出格式要求:"class1=%d, class2=%d, class3=%d\n" 程序运行示例如下: ghdf^%^#$^&(+-//+_8*(\ class1=1, class2=7, class3=14
时间: 2023-05-31 17:18:37 浏览: 251
### 回答1:
这是一道编程题,要求通过键盘输入任意的字符,按下列规则进行分类计数:
第一类:‘0’,‘1’,‘2’,‘3’,‘4’,‘5’,‘6’,‘7’,‘8’,‘9’
第二类:‘+’,‘-’,‘*’,‘/’,‘%’,‘=’
第三类:其他字符
然后要求用getchar()输入字符,并统计得出结果,最后输出格式为:"class1=%d, class2=%d, class3=%d\n"。示例输出:"class1=1, class2=7, class3=14\n"
### 回答2:
题目要求对输入的字符进行分类计数,共分为三类:
第一类是数字,包括从0到9的数字。
第二类是运算符,包括空格、减号、乘号、除号、百分号和等于号。
第三类是其它字符。
程序运行的基本思路是,利用getchar()从键盘输入字符,判断每个字符属于哪一类,然后对相应计数器加1。当输入的字符等于\时,停止输入并输出计数结果。
代码如下:
#include<stdio.h>
int main()
{
int ch, class1 = 0, class2 = 0, class3 = 0;
while ((ch = getchar()) != '\\') //当输入字符等于\时终止循环
{
if (ch >= '0' && ch <= '9') //数字
{
class1++;
}
else if (ch == ' ' || ch == '-' || ch == '*' || ch == '/' || ch == '%' || ch == '=') //运算符
{
class2++;
}
else //其他字符
{
class3++;
}
}
printf("class1=%d, class2=%d, class3=%d\\n", class1, class2, class3);
return 0;
}
我们通过一个while循环,不断使用getchar()读取输入的字符,并根据字符的种类分别对计数器进行加1。当读取到最后一个字符\时,跳出循环并输出计数结果。在输出时注意需要转义\字符。
我们可以针对不同的输入,进行测试,比如输入:
234+8675abc%de-f=
程序的输出结果应该为:
class1=8, class2=6, class3=6
其中数字8表示输入中包含了8个数字,数字6表示输入中包含了6个运算符,而数字6则表示输入中包含了6个其他字符。
### 回答3:
题目要求我们从键盘输入任意的字符,并按照规则进行分类计数。共分为三类,第一类为0~9数字,第二类为空格,减号,乘号,除号,百分号,等号,第三类为其它字符。
那么我们可以编写一个while循环,每次输入一个字符,通过switch语句进行分类计数,直到遇到结束符。
下面是具体的代码实现:
```c
#include <stdio.h>
int main() {
int c;
int class1 = 0, class2 = 0, class3 = 0;
while ((c = getchar()) != '\\') {
switch (c) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
class1++;
break;
case ' ':
case '-':
case '*':
case '/':
case '%':
case '=':
class2++;
break;
default:
class3++;
break;
}
}
printf("class1=%d, class2=%d, class3=%d\\n", class1, class2, class3);
return 0;
}
```
在这里,我首先声明了三个计数变量,然后使用了一个while循环,每次使用getchar()函数输入一个字符,如果不是结束符,则进入switch语句进行分类。对于第一类字符,我使用了多个case语句合并,这样可以让代码更加简洁。
最后,输出每一类字符的个数,其中第三类字符包括结束符\。注意,在输出中需要使用\\表示一个反斜杠。
程序运行示例如下:
输入:ghdf^%^\
输出:class1=0, class2=6, class3=4
希望我的回答能够对你有所帮助!
阅读全文
相关推荐


















