統計 1 到 100 (含) 之間奇數的個數。
#include
#define BEGIN 1
#define END 100
int main(void) {
int count = 0;
for (int i = BEGIN; i <= END; ++i) {
if (i % 2 == 1) {
++count;
}
}
printf("1 到 %d 之間奇數個數 = %d\n", END, count);
return 0;
}
1 到 100 之間奇數個數 = 50
1, 3, 5, ..., 99 為等差數列,項數 n = (99 - 1) / 2 + 1 = 50。
for (int i = BEGIN | 1; i <= END; i += 2) ++count;
int first = (BEGIN % 2) ? BEGIN : BEGIN + 1;
int last = (END % 2) ? END : END - 1;
int count = (first <= last) ? (last - first) / 2 + 1 : 0;
#define END 100 **不加分號**。i <= END 含邊界。count **必須初始化為 0**。++count 前置遞增語意清晰且效能略優。int begin, end;
printf("請輸入起始與結束值:");
scanf("%d %d", &begin, &end);
if (begin > end) { int t = begin; begin = end; end = t; } // 交換確保 begin <= end
// 後續邏輯同前