首先我们先来分析一下题目的意思:1~n中有多少个9,什么意思呢,举个例子:1~100中有多少个9,大家肯定一下子就会觉得简单啊,直接对所有数取模10等于9的不就是嘛。仔细分析一下,这么想对吗?很明显不对啊,90、91、92……这些除个位之外其它位上也可能有9,所以正确的是将各位上的9数一下即为正解。那么怎么操作呢?很简单,我们先将个位上的9计数,然后对该数字除10,重复上一步操作然后把所有的计数累加即为所求。下面让我们来看源程序:
#include <stdio.h>
int count_9(int n)//模10取余法
{
int count = 0;
while(n != 0)
{
if(n % 10 == 9)//判断该数字对10取模是否为9
{
count++;
}
n = n / 10;//将该数字缩小一位
}
return count;//返回count
}
int main()
{
int n;
int i;
int count = 0;
printf("please enter a number:");
scanf("%d",&n);
for(i = 1;i <= n;i++)
{
count = count + count_9(i);
}
printf("count = %d\n",count);
return 0;
}