題目:對學員的結業考試成績進行評測
成績>=90: A
90>成績>=80: B
80>成績>=70:C
70>成績>=60:D
解法1:沒有理解if Else if本質,而且這種錯誤很容易犯
if (score >= 90) // 條件1 { Console.WriteLine("A"); } else if (80 =< score && score < 90) //條件2 這里的score<90根本不執行,沒有理解if else if的本質 { Console.WriteLine("B"); } // ...
上面的寫法實際上沒有理解if else if的本質
if else if的本質是:如果if條件不滿足則執行Else中的條件判斷。基於這個理解,上面的if語句條件1不滿足的話,實際上就意味着score《90
所以條件2中的子條件score<90是多次一舉!
或者else if (score<90 && score <=80) ,這里的Score<90 在條件1為假后,肯定為真!
解法2:數學思維,編譯通不過
if (80 <= score < 90) // BUILD ERROR: Operator '<' cannot be applied to operands of type 'bool' and 'int' { Console.WriteLine("B"); }
正確寫法
Console.WriteLine("請輸入的你的成績"); int score = Convert.ToInt32(Console.ReadLine()); if (score >= 90) { Console.WriteLine("A"); } else if (score >= 80) { Console.WriteLine("B"); } else if (score >= 70) { Console.WriteLine("C"); } else if (score >= 60) { Console.WriteLine("D"); }
題目:比較用戶名和密碼是否正確並輸入相應的提示
提示用戶輸入用戶名,然后再提示用戶輸入密碼,如果用戶名是"admin"和密碼是"888888",那么提示正確
否則,如果用戶名不是Admin,則提示用戶名不存在,如果用戶名是Admin則提示密碼不正確.
static void Main(string[] args) { Console.WriteLine("請輸入用戶名"); string username = Console.ReadLine(); Console.WriteLine("請輸入密碼"); string password = Console.ReadLine(); if (username == "admin" && password == "888888") { Console.WriteLine("密碼正確"); } else { if (username != "admin") { Console.WriteLine("用戶名不正確"); } else if (password != "888888") { Console.WriteLine("密碼不正確"); } } Console.ReadKey(); }
上面的寫法,是Else里面嵌套了If Else。下面采用另外一種寫法,是If Else If Else
class Program { static void Main(string[] args) { Console.WriteLine("請輸入你的用戶名"); string username = Console.ReadLine(); Console.WriteLine("請輸入你的密碼"); string password = Console.ReadLine(); // 下面的If Else If Else 可以成對理解,比如else if else 還是可以作為一個來理解 if (username == "admin" && password == "888888") { Console.WriteLine("用戶名和密碼正確"); } else if (username != "admin") { Console.WriteLine("用戶名不正確"); } else // 注意理解上面If Else If { Console.WriteLine("密碼不正確"); } Console.ReadKey(); } }
If Else 語句是否使用{}
通常if表達式后只有一個語句的話,不使用{}.同樣的下面的形式卻有不同的結果.
if (true) string test ="test"; // 這個會發生編譯錯誤! if (true) { string test = "test"; // 這樣子的寫法正確 }
Else與靠近If結合
如果if 表達式后面只有一個語句,通常會不寫{},但是這個習慣也可能導致程序出現BUG,比如下面的代碼
class Program { static void Main(string[] args) { int age = 15; char sex = 'f'; if (age <10) if (sex == 'f') Console.WriteLine("小女人"); else //注意else只和最近if結合,所以這道題什么都不輸出 Console.WriteLine("你長大了"); Console.ReadKey(); } }
總結:在實際情況下,通常以為自己會If Else,但是實際上If Else的組合起來可以構造非常復雜的業務邏輯.而且好的
If Else組合一看就明白業務含義,但是差的If Else就容易誤導或者非常難理解這段If Else的含義.
總之一句話,多多練習怎么用語言來表達If Else的含義.只有這樣才能理解了程序的業務邏輯和業務規則怎么用編程語言來描述.
最后:If Else 和While的使用水平高低決定你編程能力的高低!
程序只有順序,分支,循環三種基本結構.熟練掌握這些基本結構非常重要.