經典數字統計問題,通過百位、十位、個位分解檢查,展示整數拆解與計數邏輯。
對每個數 num:
hundred = num / 100; // 百位
ten = (num % 100) / 10; // 十位
unit = num % 10; // 個位
分別判斷三位是否為 9,累加計數。
#include
int main() {
int count = 0;
for (int num = 1; num <= 100; num++) {
int hundred = num / 100;
int ten = (num % 100) / 10;
int unit = num % 10;
if (hundred == 9) count++;
if (ten == 9) count++;
if (unit == 9) count++;
}
printf("9出現的個數:\n%d\n", count);
return 0;
}
9出現的個數: 20
通用化統計任意範圍 [1, N] 中數字 d 出現次數:
本題通過直觀的位拆解法,強化整數運算與循環累加基本功。