C# 《五》流程控制(1)
阿新 • • 發佈:2017-08-27
generic ram div 執行 進行 運行 align strong c#
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)