日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

c语言switch语句程序大全,C语言switch语句

發(fā)布時間:2025/5/22 编程问答 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 c语言switch语句程序大全,C语言switch语句 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

C語言中的switch語句用于從多個條件執(zhí)行代碼。 就像if else-if語句一樣。

C語言中switch語句的語法如下:

switch(expression){ case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional ...... default: code to be executed if all cases are not matched; }

C語言中switch語句的規(guī)則如下 –

switch表達式必須是整數(shù)或字符類型。

case值必須是整數(shù)或字符常量。

case值只能在switch語句中使用。

switch case中的break語句不是必須的。這是一個可選項。 如果在switch case中沒有使用break語句,則匹配case值后將執(zhí)行所有后的語句。它被稱為通過C語言switch語句的狀態(tài)。

我們試著通過例子來理解它。假設(shè)有以下變量及賦值。

int x,y,z; char a,b; float f;

有效的Switch

無效的Switch

有效的Case

無效的Case

switch(x)

switch(f)

case 3;

case 2.5;

switch(x>y)

switch(x+2.5)

case ‘a(chǎn)’;

case x;

switch(a+b-2)

case 1+2;

case x+2;

switch(func(x,y))

case ‘x’>’y’;

case 1,2,3;

C語言中的switch語句的流程圖 –

我們來看一個簡單的C語言switch語句示例。創(chuàng)建一個源文件:switch-statment.c,其代碼如下 –

#include #include void main() { int number = 0; printf("Enter a number:"); scanf("%d", &number); switch (number) { case 10: printf("number is equals to 10n"); break; case 50: printf("number is equal to 50n"); break; case 100: printf("number is equal to 100n"); break; default: printf("number is not equal to 10, 50 or 100n"); } }

執(zhí)行上面示例代碼,得到以下結(jié)果 –

Enter a number:88 number is not equal to 10, 50 or 100

執(zhí)行第二次,結(jié)果如下 –

Enter a number:50 number is equal to 50 請按任意鍵繼續(xù). . .

switch語句直通到尾

在C語言中,switch語句是通過的,這意味著如果在switch case中不使用break語句,則匹配某個case之后的所有的case都將被執(zhí)行。

我們來試試通過下面的例子來了解switch語句的狀態(tài)。創(chuàng)建一個源文件:switch-fall-through.c,其代碼如下所示 –

#include #include void main() { int number = 0; printf("enter a number:"); scanf("%d", &number); switch (number) { case 10: printf("number is equals to 10n"); case 50: printf("number is equal to 50n"); case 100: printf("number is equal to 100n"); default: printf("number is not equal to 10, 50 or 100n"); } }

執(zhí)行上面示例代碼,得到以下結(jié)果 –

enter a number:10 number is equals to 10 number is equal to 50 number is equal to 100 number is not equal to 10, 50 or 100 請按任意鍵繼續(xù). . .

從上面的輸出結(jié)果中,可以清楚地看到,當匹配 number = 10 之后,由于沒有break語句,其它后面的語句也打印執(zhí)行了。

¥ 我要打賞?? 糾錯/補充 收藏

總結(jié)

以上是生活随笔為你收集整理的c语言switch语句程序大全,C语言switch语句的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。