- C 程式設計有用的資源
- 透過示例學習 C - 快速指南
- 透過示例學習 C - 資源
- 透過示例學習 C - 討論
比較 C 中的三個整數
比較三個整數變數是你輕鬆編寫的最簡單的程式之一。在此程式中,你可以使用 scanf() 函式從使用者那裡獲取輸入,或者直接在程式本身中靜態定義。
我們希望它對你來說也是一項簡單的程式。我們將一個值與另外兩個值進行比較,並檢查結果,並且對所有變數都應用相同的流程。對於此程式,所有值都應該是不同的(唯一的)。
演算法
讓我們首先看看比較三個整數的分步過程 -
START Step 1 → Take two integer variables, say A, B& C Step 2 → Assign values to variables Step 3 → If A is greater than B & C, Display A is largest value Step 4 → If B is greater than A & C, Display B is largest value Step 5 → If C is greater than A & B, Display A is largest value Step 6 → Otherwise, Display A, B & C are not unique values STOP
流程圖
我們可以為此程式繪製出如下所示的流程圖 -
此圖表顯示了三個 if-else-if 和一個 else 比較語句。
虛擬碼
現在,讓我們看看此演算法的虛擬碼 -
procedure compare(A, B, C)
IF A is greater than B AND A is greater than C
DISPLAY "A is the largest."
ELSE IF B is greater than A AND A is greater than C
DISPLAY "B is the largest."
ELSE IF C is greater than A AND A is greater than B
DISPLAY "C is the largest."
ELSE
DISPLAY "Values not unique."
END IF
end procedure
實現
現在,我們將看到程式的實際實現 -
#include <stdio.h>
int main() {
int a, b, c;
a = 11;
b = 22;
c = 33;
if ( a > b && a > c )
printf("%d is the largest.", a);
else if ( b > a && b > c )
printf("%d is the largest.", b);
else if ( c > a && c > b )
printf("%d is the largest.", c);
else
printf("Values are not unique");
return 0;
}
輸出
此程式的輸出應該是 -
33 is the largest.
simple_programs_in_c.htm
廣告