題目描述
- 每行第一個整數
n (n<100) 表示後續有 n 個實數
- 統計這
n 個數中負數、零、正數的個數
n=0 結束輸入
樣例
Input:
6 0 1 2 3 -1 0
5 1 2 3 4 0.5
0
Output:
1 2 3 // 負1個,零2個,正3個
0 0 5 // 全非負,5個正數
解題邏輯
- 外層循環讀
n,n==0 跳出
- 初始化
neg=zero=pos=0
- 內層循環
n 次讀 double x,三向分支累加
- 輸出三計數
代碼
#include <stdio.h>
int main() {
int n, neg, zero, pos;
double x;
while (scanf("%d", &n) == 1 && n != 0) {
neg = zero = pos = 0;
while (n--) {
scanf("%lf", &x);
if (x < 0) neg++;
else if (x == 0) zero++;
else pos++;
}
printf("%d %d %d\n", neg, zero, pos);
}
return 0;
}
關鍵點
- 實數比較
x == 0 在輸入為精確 0 或 0.0 時安全;若涉及運算誤差需用 fabs(x) < eps
while (n--) 簡潔實現計數循環
- 輸入以
n=0 終止,非 EOF,注意循環條件