Presentation is loading. Please wait.

Presentation is loading. Please wait.

If … else 選擇結構 P27.

Similar presentations


Presentation on theme: "If … else 選擇結構 P27."— Presentation transcript:

1 if … else 選擇結構 P27

2 寫程式時,如需判斷狀況,給予不同回應,則可使用if選擇結構
條件 true flase

3 if else 流程圖P28 前面程式 條件判斷 false true 敘述t1; 敘述tn; else 敘述f1; 敘述fn; 後面程式

4 if 流程圖P27 前面程式 條件判斷 false true 敘述t1; 敘述tn; 後面程式

5 if 程式語法 if (判斷條件) { … 敘述tn; } else { 敘述fn; 敘述t1; 敘述f1;
二元運算子--關係運算子(運算結果為true 或 false) > < >= <= == != 二元運算子--邏輯運算子(運算結果為true 或 false) && || true false

6 判斷輸入的數字是否大於0 int num; scanf(“%d”,&num); if(num>=0)
printf(“您輸入的數字大於或等於0\n"); else printf(“您輸入的數字小於0\n");

7 判斷式 單一判斷式 if(num>=0) printf(“您輸入的數字大於或等於0\n"); 複合判斷式
if(num>=0 && num<21) printf … 0 <= num < 21

8 輸入都為真all are true時,輸出為真
and(且) && 輸入都為真all are true時,輸出為真 or(或) || 輸入任一為真everyone is true時,輸出為真 s1 && s2 s2 T F s1 s1 || s2 s2 T F s1

9 運算子優先順序 優先順序 運算子 結合順序 1 ( )、[ ]、 -> 左到右 2 !、+(正)、-(負)、++、-- 右到左 3
( )、[ ]、 -> 左到右 2 !、+(正)、-(負)、++、-- 右到左 3 *、/、% 4 +、- 5 <<、>> 6 >、>=、<、<= 7 == 、!= 8 && 9 || 10 =、+=、-=、*=、/=、%=

10 判斷條件中,是否相等的「=」要使用二個 == 例: if(num%5 == 0) 提醒2 敘述只有1行時,可以不用加 { }
提醒1 判斷條件中,是否相等的「=」要使用二個 == 例: if(num%5 == 0) 提醒2   敘述只有1行時,可以不用加 { } int num; scanf(“%d”,&num); if(num>=0) printf(“您輸入的數字大於或等於0\n"); else printf(“您輸入的數字小於0\n");

11 輸入兩個整數a,b,利用if敘述,判斷當a>b時,印出a+b及a-b的值,無論判斷條件是否成立,皆印出a*b的結果
#include <stdio.h> int main(){ int a,b;   printf("first number second number "); /*輸入兩個整數a、b*/ scanf("%d %d",&a,&b);  if (a>b) printf("a+b=%d\n",a+b); printf("a-b=%d\n",a-b); printf(“a*b=%d\n”,a*b); return 0; } { } 後面程式 後面程式

12 輸入一整數num,判斷其為奇數或偶數 num %2 == 0 num num int num; scanf(”%d”,&num);
if ( ) printf(“%d為偶數”, ); else printf(“%d為奇數”, ); num %2 == 0 num num


Download ppt "If … else 選擇結構 P27."

Similar presentations


Ads by Google