您的位置:首页 > 其它

整数算法训练01—统计1~n有多少个9

2017-08-04 15:14 281 查看
/*******************************************

  通过编程实现“统计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 ;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: