之前学循环时,曾经做过只要计算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;
}