在 C 中查詢正負數程式



就像找出數字是偶數還是奇數,找出數字是正數還是負數,也是一項非常簡單的程式。我們將在 C 中學習如何使用條件語句 if-else

演算法

該程式的演算法非常簡單 −

START
   Step 1 → Take integer variable A
   Step 2 → Assign value to the variable
   Step 3 → Check if A is greater than or equal to 0  
   Step 4 → If true print A is positive
   Step 5 → If false print A is negative
STOP

流程圖

我們可以繪製此程式的流程圖,如下所示 −

FlowDiagram Positive or Negative

虛擬碼

procedure positive_negative()

   IF ( number ≥ 0 )
      PRINT number is positive
   ELSE
      PRINT number is negative
   END IF

end procedure

實現

此演算法的實現如下 −

#include <stdio.h>

int main() {
   int number = -2;
   
   if (number >= 0)
      printf("%d is positive\n", number);
   else
      printf("%d is negative\n", number);
   
   return 0;
}

輸出

程式的輸出應為 −

-2 is negative
simple_programs_in_c.htm
廣告
© . All rights reserved.