首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

HDU 數值統計:負數、零、正數計數器

     編輯:關於C語言

題目描述

  • 每行第一個整數 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個正數

解題邏輯

  1. 外層循環讀 n,n==0 跳出
  2. 初始化 neg=zero=pos=0
  3. 內層循環 n 次讀 double x,三向分支累加
  4. 輸出三計數

代碼

#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,注意循環條件
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved