if-else判斷語句中常常犯的一個錯誤

假設題目爲:隨便給定一個數,三種狀況:(1)若小於0,輸出爲「小於0」;(2)若在0-50之間,則輸出「在0-50之間」。(3)若大於50,則輸出「大於50」。

解法:若是我這麼寫,運行一下看看。spa

            int x = Convert.ToInt16(Console.ReadLine());

            if (x>50)
            {
                Console.WriteLine("超過50");
            }
            if(x>0 && x<50)
            {
                Console.WriteLine("在0到50之間");
            }
            else
            {
                Console.WriteLine("小於0");
            }

 

        當輸入小於0和0-50之間的數時,均正常輸出,可是!!!當輸出大於50的時候,就出現瞭如上圖所示的問題:輸入59之後,不但輸出了超過50,還輸入了小於0,這顯然不是我要的結果!!!code

        爲什麼呢?這就涉及else的運行原理了:else會在上一個if判斷爲false時執行!!這時候能夠把else和他最鄰近的上一個if組成一對。blog

        因此,該題目代碼可修改成:it

            int x = Convert.ToInt16(Console.ReadLine());

            if (x>50)
            {
                Console.WriteLine("超過50");
            }
            else if(x>0 && x<50)
            {
                Console.WriteLine("在0到50之間");
            }
            else
            {
                Console.WriteLine("小於0");
            }

        僅僅只須要在第二個if前加一個else便可,固然,通常的的問題也不會這麼簡單,可是明白了這個道理之後,是否是能夠更好的處理問題了呢?class

相關文章
相關標籤/搜索