-
1 # fsryd16344
-
2 # 滴逃逃
switch 叫開關語句,根據條件判斷,選擇某些語句執行。
句法:
switch (k)
{
case 1: ...; break;
case 4: ...; break;
case 3: ...; break;
default: ...;break;
}
k 是 現在給的值
case 與冒號之間是條件,現在給的值滿足哪個 case 與冒號之間的條件,就執行冒號以下的語句,直到break跳出開關語句。
所有的case 與冒號之間的條件都不滿足時,執行default以下的語句直到break。
下面給個例項--拍入兩個數,選加,或減或乘或除,程式用開關語句判斷,選擇執行,並打出算式和結果。
#include
#include
void main(){
float s1 = 0, s2 = 0; /* the two numbers to work on */
int menu = 1; /* add or substract or divide or multiply */
float total = 0; /* the result of the calculation */
char calType; /* what type of calculation */
printf("Please enter s1 \n\t");
scanf("%f", &s1); /* READ first number */
printf("Please enter s2 \n\t");
scanf("%f", &s2); /* READ second number */
printf("\n\nWhat would you like to do?\n\n");
printf("\t1 = add\n");
printf("\t2 = substract\n");
printf("\t3 = multiply\n");
printf("\t4 = divide\n");
printf("\n\nPleas make your selection now:\n\t");
scanf("%d",&menu); /* READ calculation type */
switch (menu)
{
case 1: total = s1 + s2;
calType = "+";
break;
case 2: total = s1 - s2;
calType = "-";
break;
case 3: total = s1 * s2;
calType = "*";
break;
case 4: total = s1 / s2;
calType = "/";
break;
default: printf("Invalid option selected\n");
}
printf("\n\n*************************");
printf("\n\n %.3f %c %.3f = %.2f", s1, calType, s2, total);
printf("\n\n*************************\n\n");
}
[選除法時,除數別給0]
回覆列表
1、SWITCH語句的字面意思是開關,是用來進行多重選擇。具體的用法首先開啟C-Free5.0軟體,然後新建一個名為switch.c檔案,然後在引入標頭檔案和main主函式:
2、首先定義一個整型數值,然後從外面寫入這個值,這裡用到的scanf函式就是從外面讀入一個值給a,然後執行一下,輸入一個數驗證:
3、接著用switch先判斷獲得是什麼值,按照獲得的值來執行相應的步驟,注意這裡輸入的值必須是定義的值,否則switch語句的條件不會被觸發;最後的default則是用來判斷不滿足以上條件用的,不滿足的時候這裡打印出另一句話告訴使用者輸入非法了:
4、最後編譯除錯下程式,看看對不對, 當輸入1-5任意一個值的時候,螢幕上會打印出相應的語句。以上就是c語言中switch語句的用法: