C语言学习历程——Traing01整数算法训练01

来源:互联网 发布:java开源 编辑:程序博客网 时间:2024/05/16 14:30

1. 题目:通过编程实现,统计1~n有多少个9

 提示:n通过参数传入

 分析:题目的意思是这样的,输入19,应该是有9,19两个带‘9’的数字,所以输出2,那思路就有了,遍历输入的数字,查询出现了多少次‘9’,用计数器记录即可

下面是代码实现:

/*******************************************
  通过编程实现“统计1~n一共出现了多少次9”
  例如29  出现了3次9   输出3
  n通过参数传入
 ******************************************/


#include<stdio.h>


int TimesOfNine(int n)
{
    int i = 0;
    int count = 0;                                                            //计数器,统计'9'出现的次数
    int tmp1 = 0;
int tmp2 = 0;

for (i = 1; i <= n; i++)
{
tmp1 = i;
while (tmp1)  //如果是9,那么直接计数器加一
{
if (tmp1 == 9)
{
count++;
}
else
{
tmp2 = tmp1 % 10; //否则求出个位数,再判断是否为9
if (tmp2 == 9)
{
count++;
}
}
tmp1 /= 10;
}
}

return count;  //返回次数
}


int main()
{
int n = 0;

    printf("please input a number(1~n):");
    scanf("%d",&n);


    printf("count = %d\n",TimesOfNine(n));  //打印结果
    return 0 ;
}

0 0
原创粉丝点击