標籤:string 9.png space namespace ... 分支語句 路徑 不能 程式設計語言
1、分支語句之 if 語句
1、流程式控制制語句是程式的核心部分,對任何一門程式設計語言來說都至關重要,是控製程序執行流向的基本語句。如果一門語言缺少了流程式控制制,就會缺少對程式流向的控制,就不能稱之為電腦語言。
2、C#語言提供了豐富、靈活的控制流程程語句,主要分分支語句、迭代語句、跳躍陳述式三類。
分支語句為 if 語句與 switch 語句;能夠根據實際情況決定邏輯路徑代碼。
if(判斷條件運算式){ //運算式結果為 true 時執行} else{ //運算式結果為 false 時執行}
3、對輸入的數字進行判斷
> 10 提示大於 10
< 10 提示小於 10
= 10 提示等於 10
4、新語句
int Parse(Console.ReadLine()); //接受使用者輸入的整數
程式如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace _5._1_分支語句_if_語句{ class Program { static void Main(string[] args) { //判斷變數 a 中存放數值與 10 的關係 Console.WriteLine("請輸入數值,判斷它與 10 的關係:"); int a = int.Parse(Console.ReadLine()); //int.Parse 用於將螢幕輸入的語句轉換為整型 if(a < 10) { Console.WriteLine("a小於 10"); } if(a == 10) { Console.WriteLine("a 等於 10"); } if(a > 10) { Console.WriteLine("a 大於 10"); }/* else //如果前邊的 if 語句一條也沒有執行,那就執行 else 語句 //如果執行了其中一條 if 語句,那就不會執行else語句 { Console.WriteLine("無法判斷"); }*/ Console.ReadKey(); } }}
運行結果:
2、分支語句之swirch 語句
執行個體:
1、輸入 1 顯示為星期一,依此類推
程式如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace _5._2分支語句之switch語句{ class Program { static void Main(string[] args) { //輸入 1 顯示星期一,依次類推 Console.WriteLine("請輸入1-7中的一個數字"); int week = int.Parse(Console.ReadLine()); //if (week == 1) Console.WriteLine("星期一"); //if (week == 2) Console.WriteLine("星期二"); //if (week == 3) Console.WriteLine("星期三"); //if (week == 4) Console.WriteLine("星期四"); //if (week == 5) Console.WriteLine("星期五"); //if (week == 6) Console.WriteLine("星期六"); //if (week == 7) Console.WriteLine("星期天"); switch(week) { case 1: Console.WriteLine("星期一"); break; case 2: Console.WriteLine("星期二"); break; case 3: Console.WriteLine("星期三"); break; case 4: Console.WriteLine("星期四"); break; case 5: Console.WriteLine("星期五"); break; case 6: Console.WriteLine("星期六"); break; case 7: Console.WriteLine("星期七"); break; default: Console.WriteLine("您的輸入有誤"); break; } Console.ReadKey(); } }}
運行結果:
2、判斷2015年每個月份的天數
程式如下:
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace _5._2分支語句之switch語句{ class Program { static void Main(string[] args) { //判斷2015年每個月的天數 //31天:1、3、5、7、8、10、12 //30天:4、6、9、11 //28天:2 Console.WriteLine("請輸入月份數字"); int month = int.Parse(Console.ReadLine()); switch(month) { case 2: Console.WriteLine("本月有28天"); break; case 4: case 6: case 9: case 11: Console.WriteLine("本月有30天"); break; default: Console.WriteLine("本月有31天"); break; } Console.ReadKey(); } }}
運行結果:
1、結構:
switch(運算式){ case 常量運算式: 條件陳述式; case 常量運算式: 條件陳述式; case 常量運算式: 條件陳述式; case 常量運算式: 條件陳述式; ...... default: 條件陳述式;}
C# 《五》流程式控制制(1)