寻光


私信TA

用户名:RITD

访问量:22672

签 名:

追寻最优解

等  级
排  名 543
经  验 4312
参赛次数 0
文章发表 13
年  龄 20
在职情况 学生
学  校 East Electricity
专  业 计科

  自我简介:

很菜所以很努力

TA的其他文章

解题思路: 此题可用两种方法来做

方法一:

1.了解ASCII表,那些字符在哪里,用那些字符对应的数字,也可不用了解,直接用字符就行

2.要声明4个变量分别记录题目(字母、数字、空格、其他字符)要求的数量,和一个字符变量利用getchar()获得赋值

3.用getchar()利用while循环读取字符,while循环里用if else嵌套给对应的字符数加一

 4.利用printf()输出出来

方法二:

如果对gets(),strlen(),数组不了解的话,此法可不看

1.先声明一个数组用于gets()来存储输入

声明4个变量来存储对应的字符数

2.strlen()获取输入的长度,用于后面的for循环

3.利用for循环计算各字符数

20200728090157350.png
注意事项: 注意while循环里里面的条件

参考代码:

1.利用getchar()

#include <stdio.h>
int
main(void)
{
	int letter = 0, number = 0, space = 0, other = 0;
	char ch;
	
	while( (ch = getchar()) != '\n'){     /*这里的‘\n’不能换成EOF,要不就把输入的换行符输入进来当成其他字符处理,
	                                        因此其他字符的数量将比题目所给的数量多一*/
	    if ((ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
	    	letter += 1;   //letter表示字母数量
	    else
		if (ch == ' ')
	    	    space += 1;  //空格数量
	    	else
		    if (ch >= '0' && ch <= '9')
	    		number += 1; //数字数量
	    	    else
	    		other += 1;  //其他字符数量
	}
	printf("%d %d %d %d", letter, number, space, other);
	
	return 0;
}

ii:for(),数组处理

#include <stdio.h>
#include <string.h> 
int
main(void)
{
	char str[200];//声明一个数组用于存储输入的字符
	int letter = 0, number = 0, space = 0, other, n;
	
	gets(str); //获取输入并存储到数组里,gets会把输入的换行符\n丢弃
	n = strlen (str); //获取输入的字符长度
	
	
	
	for(int i = 0; i < n; i++)//for循环可以声明变量同时初始化,多个声明用 , 逗号隔开
	{
		if ((str[i] >= 'A' && str[i] <= 'Z') || (str[i] >= 'a' && str[i] <= 'z'))
			letter += 1;
		if (str[i] == ' ')
		    space += 1;
		if (str[i] >= '0' && str[i] <= '9')
			number += 1;		 
	}
	other = n - space - number - letter; //把整个字符长度减去字母数、空格、数字得出其他字符的数量
	
	printf("%d %d %d %d", letter, number, space, other);
	
	return 0;
}


 

0.0分

84 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换

万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区

#include<stdio.h>
int main()
{
	int a,b,c,d;
	char h;
	//printf("请输入一行字符串:");
	while((h=getchar())!='\n')
	{
		if(h>='a'&&h<='z'||h>='A'&&h<='Z')
		{
			a++;
		}
		else if(h>='0'&&h<='9')
		{
			b++;
		}
		else if(h==' ')
		{
			c++;
		}
		else
		{
			d++;
		}
	}
	printf("%d %d %d %d",a,b,c,d);
	return 0;
}
我的这个为什么结果中数字字符总是多一个呢
2023-09-17 10:35:45
#include<stdio.h>
int main()
{
	int a,b,c,d;
	char h;
	printf("请输入一行字符串:");
	getchar();
	h=getchar();
	while(h!='\n')
	{
		if(h>='a'&&h<='z'||h>='A'&&h<='Z')
		{
			a++;
		}
		else if(h>='0'&&h<='9')
		{
			b++;
		}
		else if(h==' ')
		{
			c++;
		}
		else
		{
			d++;
		}
	}
	printf("字母个数:%d,数字个数:%d %d %d",a,b,c,d);
	return 0;
}
各位大神可以看看我哪里错了吗?
2023-09-17 10:13:16
第一个表示输入的东西在哪啊,不用单独写一个getchar()吗
2023-08-08 10:14:31
为什么不能用<ctype.h>里的函数统计呀,是错误的?
2022-11-12 16:38:40
想问下楼主,第一个方法为什么在第7行输入ch=getchar()再把while后面括号里的改为ch!='\n'就显示时间超限了呢?
2022-10-06 20:56:15
while循环的条件没看懂,为什么是\n?
2022-09-27 10:31:50