C语言判断一个整型数据有几位v2.0

题目内容:

从键盘输入一个整型数据(int型),编写程序判断该整数共有几位,并输出包含各个数字的个数。例如,从键盘输入整数16644,该整数共有5位,其中有1个1,2个6,2个4。

程序运行结果示例1:

Please enter the number:

12226↙

12226: 5 bits

1: 1

2: 3

6: 1

程序运行结果示例2:

Please enter the number:

-12243↙

-12243: 5 bits

1: 1

2: 2

3: 1

4: 1

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
    int n,x,count=0,a[10],i;
	printf("Please enter the number:\n");
    scanf("%d",&n);
    x=fabs(n);//为了下面的输出以及负数的出现而做出的绝对值赋值
    for(i=0;i<=9;i++) //初始化数组
		a[i]=0;
    while(x!=0)//这个外循环是为了判断输入数据的位数
    {	
        for(i=0;i<=9;i++)//内层循环是为了计算每个位数的数出现的次数
        {
            if (x%10==i)
				a[i]++;
        }
		x/=10;
        count++;
    }
	printf("%d: %d bits\n",n,count);
    for(i=0;i<=9;i++)//循环输出打印
    {	
        if (a[i] != 0)//筛选输出
			printf("%d: %d\n",i,a[i]);
    }
    
	system("pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_42833469/article/details/88352530