C语言 读入1个整数,统计并办理出该数中2的个数。

如题所述

C语言实现如下:

#include<stdio.h>
#include<string.h>
void main()
{
int i,sum=0,len;
char c[1000];
gets(c);  //以字符数组的形式储存读入一个整数各个位上的数。
len=strlen(c);
for(i=0;i<len;i++)
if (c[i]=='2') sum++; //判断各个位上的数是否为2,统计2的个数。
printf("%d\n",sum);  //输出该数中2的个数。
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2020-06-08
不知道你想用什么语言实现这部分功能
大体思路可以参考
先将这个整数转换成字符串,再取得该字符串的长度,通过一个循环,
result:=
0
for
i:=
0
to
length(字符串)-1
do
...
if
...then
result:=
result+1;
end
for-loop
逐一字符和‘2’比较。比较结果计数累加,即得结果。
有些已经提供了丰富的字符串函数,可能就不用这么逐个比较的办法,就更简单了。
第2个回答  2009-04-30
#include<stdio.h>
void main()
{ int a,i=0;
printf("Please input an integer: ");
scanf("%d", &a);
while(a!=0)
{if(a%10==2)
i++;
a=a/10;}
printf("该数中2的个数=%d\n",i);

}
第3个回答  2009-04-30
是这个意思不?

#include <stdio.h>
#include <string.h>
int main()
{
int a, length, ii, num;
char b[20];

printf("Please input an integer: ");
scanf("%d", &a);

sprintf(b, "%d" , a);

length = strlen(b);
num = 0;
for (ii = 0; ii < length; ++ii) {
if (b[ii] == '2') ++num;
}

printf("The number of 2 is %d in the integer %d \n", num, a);

return 0;
}本回答被提问者采纳
第4个回答  2009-04-30
#include <stdio.h>

int main()
{
int x = 0;
char array[32] = {0};

printf("Enter a integer : ");
scanf("%d", &x);
snprintf(array, sizeof(array), "%d", x);

int count = 0;
char* p = array;
for(; *p != '\0'; p++)
{
if(*p == '2')
count++;
}
printf("The count of 2 is %d int the %d\n", count, x);

return 0;
}