求1-100中数字‘9’出现的次数

来源:互联网 发布:买黄金软件下载 编辑:程序博客网 时间:2024/06/05 11:54

这是今天接触的一个有意思的小程序,我前前后后修改了三次才得到正确结果,这题目看起来很简单,但一写就错,包括之前看到很多其他博客的答案都是错的,吃透这种算法对于初学者来说很有帮助。

#include<stdio.h>#include<math.h>#include<string>int main(){    int number = 0;    int tens = 0;    int units = 0;     int count = 0;    for (number = 1; number <= 100; number++)    {        tens = (number) / 10;        units = number - tens * 10;        if (tens == 9)   //十位上出现‘9’的次数        {            count++;        }        if (units == 9)  //个位上出现‘9’的次数        {            count++;        }    }    printf("1-100中数字‘9’出现的次数为:%d次\n",count);    system("pause");    return 0;}