題目要求
- 每行第一個數
n 表示後續有 n 個整數
- 求這
n 個數中所有奇數的乘積
- 保證每組至少有一個奇數
- 多組輸入,EOF 結束
樣例推導
Input: 3 1 2 3
奇數: 1, 3 → 乘積 = 3
Input: 4 2 3 4 5
奇數: 3, 5 → 乘積 = 15
算法邏輯
- 讀
n
product = 1
- 循環
n 次讀 x,若 x % 2 != 0 則 product *= x
- 輸出
product
代碼
#include <stdio.h>
int main() {
int n, x, i;
long long product; // 防溢出用 long long
while (scanf("%d", &n) != EOF) {
product = 1;
for (i = 0; i < n; i++) {
scanf("%d", &x);
if (x % 2 == 1) product *= x;
}
printf("%lld\n", product);
}
return 0;
}
注意事項
- 乘積可能超出
int 範圍,建議用 long long(%lld)
- 負奇數
-3 % 2 == -1,條件 x % 2 == 1 會漏掉,改用 x % 2 != 0 更稳健
- 題目保證至少一個奇數,無需處理空乘積情況