- C 程式設計實用資源
- 按例程學習 C - 快速指南
- 按例程學習 C - 資源
- 按例程學習 C - 討論
用 C 比較兩個整數
比較兩個整數變數是最簡單的程式之一,你可以輕鬆編寫。在此程式中,你可以使用 scanf() 函式從使用者處獲取輸入,或在程式中靜態定義輸入。
這對我們來說也是一個簡單的程式。我們只是比較兩個整數變數。我們將首先了解演算法,然後是流程圖,隨後是虛擬碼和實現。
演算法
讓我們首先看看比較兩個整數的分步過程−
START Step 1 → Take two integer variables, say A & B Step 2 → Assign values to variables Step 3 → Compare variables if A is greater than B Step 4 → If true print A is greater than B Step 5 → If false print A is not greater than B STOP
流程圖
我們可為該程式繪製一個流程圖,如下所示−
虛擬碼
現在我們來看看此演算法的虛擬碼−
procedure compare(A, B)
IF A is greater than B
DISPLAY "A is greater than B"
ELSE
DISPLAY "A is not greater than B"
END IF
end procedure
實現
現在,我們來看一下程式的實際實現−
#include <stdio.h>
int main() {
int a, b;
a = 11;
b = 99;
// to take values from user input uncomment the below lines −
// printf("Enter value for A :");
// scanf("%d", &a);
// printf("Enter value for B :");
// scanf("%d", &b);
if(a > b)
printf("a is greater than b");
else
printf("a is not greater than b");
return 0;
}
輸出
此程式的輸出應當為−
a is not greater than b
simple_programs_in_c.htm
廣告