C语言,输入一个正整数,统计并输出数中2的个数

2024-11-25 10:17:26
推荐回答(3个)
回答1:

#include

int countdigit(int number,int digit);

int main()

{

int number,digit,result;

printf("Enter in:number=");

scanf("%d %d",&number,&digit);

result = countdigit(number,digit);

printf("countdigit(%d,%d)的返回值为:%d\n",number,digit,result);

return 0;

}

int countdigit(int number,int digit)

{

int a,i;

a=0;

i=0;

while(number!=0)

{

a=number%10;

if(a==2)

i++;

number/=10;

}

return i;

回答2:

修改如下:
1.主函数中int countdigit, digit = 2, number 中,countdigit重复定义,改为其他变量, 比如x
2.改为 scanf("%d", &number);
3.printf("Number of digit 2:%d", x); // 上述修改过后的变量x

完整修改如下:
#include
int main(void)
{
int countdigit(int number,int digit);

int x,digit=2,number;
scanf("%d",&number);
x=countdigit(number,digit);
printf("Number of digit 2:%d\n",x);
return 0;
}

int countdigit(int number,int digit)
{
int a,count=0;
while(number!=0){
a=number%10;
number=number/10;
if(a==2)
count++;
}
return count;
}

回答3:

# include
main()
{
int count(int number);
int sum,num;
printf("input the number:\n");
scanf("%d",&num);
sum=count(num);
printf("%d\n",sum);
}
int count(int a)
{
int count=0;
int yushu;
while(a!=0)
{
yushu=a%10;
a=a/10;
if(yushu==2)
count++;
}
return count;
}