首先寻找含9的数,在1~100之间,会有三种情况:
- 个位含9
- 十位含9
- 个位,十位都含9
我们知道一个整数求个位数:个位数=整数%10
例如:
87
87%10==7,即个位数为7
求十位数:十位数=整数/10
例如:
87
87/10==8,即十位数为8
具体实现代码如下:
#include <stdio.h>
#include <stdlib.h>
int main() {
int count=0; //记录出现9的次数
for (int n = 1; n <= 100;n++) {
if (n%10==9) { //个位数,满足条件,次数加一
count++;
}
if (n/10 == 9){ //十位数,满足条件,次数加一
count++;
}
}
printf("%d\n", count);
system("pause");
return 0;
}
}