如何计算一个数n从0到n中0到9出现的次数

    之前学循环时,曾经做过只要计算9出现次数的题,对于一个数n,要算出它9出现的次数,因为不知道是几位,就要从个位到十位,百位....依次计算,n就需要对10取余得到个位数与9比较,然后n除以10就是向左移一位,再对10取余就可以得出十位再与9比较,依次循环。而要得到0到n的所有数中9出现的次数,就还需要一重循环。程序如下:
#include <stdio.h>

int main()
{
    int num;

    scanf ("%d", &num);

    int i;
    int count = 0;
    for (i = 0; i <= num; i++)
    {
        int temp = i;
        while (temp)
	{
            if (temp % 10 == 9)
	    {
	        count++;
	    }
	    temp = temp / 10;
	}
    }
    
    printf ("count = %d\n", count);

    return 0;
}
     之后又需要计算0到9出现的次数,我想我可以定义10个变量来存放,就写下如下很长的程序:
#include<stdio.h>

int main()
{
    int num;

    scanf("%d", &num);

    int i;
    int count0 = 1;
    int count1 = 0;
    int count2 = 0;
    int count3 = 0;
    int count4 = 0;
    int count5 = 0;
    int count6 = 0;
    int count7 = 0;
    int count8 = 0;
    int count9 = 0;
    for (i = 0; i <= num; i++)
    {
        int temp = i;
        while (temp)
        {
            if (temp % 10 == 0)
            {
                count0++;
            }
             
            else if (temp % 10 == 1)
            {
                count1++;
            }

            else if (temp % 10 == 2)
            {
                count2++;
            }

            else if (temp % 10 == 3)
            {
                count3++;
            }

            else if (temp % 10 == 4)
            {
                count4++;
            }

            else if (temp % 10 == 5)
            {
                count5++;
            }

            else if (temp % 10 == 6)
            {
                count6++;
            }

            else if (temp % 10 == 7)
            {
                count7++;
            }

            else if (temp % 10 == 8)
            {
                count8++;
            }

            else if (temp % 10 == 9)
            {
                count9++;
            } 
            temp = temp / 10;
         }  
    }
    printf("count0 = %d\ncount1 = %d\ncount2 = %d\ncount3 = %d\ncount4 = %d\ncount5 = %d\ncount6 = %d\ncount7 = %d\ncount8 = %d\ncount9 = %d\n",count0,count1,count2,count3,count4,count5,count6,count7,count8,count9);
    return 0;
}            

     看上去这个程序非常复杂,很长,但其实思想非常简单,就是对第一个程序的复制。那么如何简化程序呢?

      在学了数组后,我发现可以定义一个数组来存放10个计数值,这样就可以简化一系列int整型的定义,源程序如下:

#include <stdio.h>

int main()
{
    int num;

	scanf ("%d", &num);

	int a[10] = {0};
	int i;


    int temp;
	for (i = 0; i <= num; i++)
	{
	    if (i == 0)
		{
		    a[i]++;
			continue;
		}
	    temp = i;
	    while (temp)
		{
		    a[temp%10]++;
			temp = temp / 10;
		}
	}

	for (i = 0; i < 10; i++)
	{
	    printf ("a[%d]: %4d\n", i, a[i]);
	}

    return 0;
}


  • 4
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值