C語言分支與循環實例代碼分析

蝸牛 互聯網技術資訊 2022-10-14 4 0

這篇文章主要介紹“C語言分支與循環實例代碼分析”,在日常操作中,相信很多人在C語言分支與循環實例代碼分析問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”C語言分支與循環實例代碼分析”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

if語句

#include?<stdio.h>

//?什么是語句?
//?C語言中由一個分號;隔開的就是一條語句
;??//?空語句

//?分支語句(選擇結構)


int?main(int?argc,?char?*argv[])
{
????int?age;
????printf("input?your?age:\n");
????scanf("%d",?&age);

????if?(age?<?18)
????????printf("You?are?underage.\n");

????if?(age?<?18)
????{
????????printf("You?are?underage.\n");
????????printf("You?can't?fall?in?love.\n");
????}
????else?if?(age?>=?18?&&?age?<?28)
????????printf("You?are?youth.\n");
????else?if?(age?>=?28?&&?age?<?50)
????????printf("You?are?in?your?prime.\n");
????else?if?(age?>=?50?&&?age?<?70)
????????printf("You?are?elderly.\n");
????else
????????printf("You?are?old.\n");

????//?懸空else問題:else和離它最近的未匹配的if匹配,和縮進無關

????//?判斷變量與常量是否相等時把常量放在左邊?5?==?num?,避免num?=?5的bug產生

????return?0;
}

switch語句

#include?<stdio.h>


int?main(int?argc,?char?*argv[])
{
????int?day;

????printf("input?a?number(1-7):?");
????scanf("%d",?&day);

????switch?(day)??//?switch后必須是整型表達式!
????{
????????case?1:??//?case后必須是整型常量表達式!
????????????printf("Monday\n");
????????????break;??//?搭配break語句實現分支
????????case?2:
????????????printf("Tuesday\n");
????????????break;
????????case?3:
????????????printf("Wednesday\n");
????????????break;
????????case?4:
????????????printf("Thursday\n");
????????????break;
????????case?5:
????????????printf("Friday\n");
????????????break;
????????case?6:
????????????printf("Saturday\n");
????????????break;
????????case?7:
????????????printf("Sunday\n");
????????????break;
????????default:???//?default不一定要寫在最后
????????????printf("%d?is?illegal?number\n",?day);
????????????break;
????}

????switch?(day)
????{
????????case?1:
????????case?2:
????????case?3:
????????case?4:
????????case?5:
????????????printf("working?day\n");
????????????break;
????????case?6:
????????case?7:
????????????printf("rest?day\n");
????????????break;
????????default:
????????????printf("%d?is?illegal?number\n",?day);
????????????break;
????}

????return?0;
}

while循環

#include?<stdio.h>


int?main(int?argc,?char?*argv[])
{
????int?i?=?1;

????while?(i?<?11)
????{
????????printf("%d?",?i);
????????++i;
????}
????printf("\n");

????return?0;
}
#include?<stdio.h>


int?main(int?argc,?char?*argv[])
{
????int?ch?=?0;

????//?輸入Ctrl+z代表EOF
????//?EOF(end?of?file),值是-1
????while?((ch?=?getchar())?!=?EOF)
????{
????????putchar(ch);
????}

????return?0;
}

到此,關于“C語言分支與循環實例代碼分析”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注蝸牛博客網站,小編會繼續努力為大家帶來更多實用的文章!

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:niceseo99@gmail.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

評論

日本韩欧美一级A片在线观看