C# Online ! 第十六篇:利用運算子,一起來做『布林邏輯』的練習題

  • 5351
  • 0
  • C#
  • 2011-07-08

C# Online ! 第十六篇:利用運算子,一起來做『布林邏輯』的練習題

大家好! 在第十五篇介紹了布林邏輯與許多的運算子,這次我們就要來練習如何運用嘍,在學習的過程中,勤加練習是一定要的! 所以各位初心者朋友,請跟著我一起練習一遍,除了比較容易理解,還可以加深印象,真是摸蜆兼洗褲一舉兩得呢!

這次的練習目標,讓我們可以輸入一個整數,然後運用布林邏輯來判斷這個整數,判斷數值是否小於10,還是介於0~5之間,最後判斷以上兩個判斷,是不是只有一個是正確的?看完練習的題目敘述以後,聰明的你是不是已經想到,可以運用哪些運算子了呢? 話不多說,接下來就趕快來練習吧!

 

STEP1:開啟專案 (圖1)

Console(圖1)

 

專案開啟完成後,會看到下面的程式碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Chapter16
{
    class Program
    {
        static void Main(string[] args)
        {
           
        }
    }
}

 

 

 

STEP2:一開始要先讓大家知道,必須先輸入一個整數,所以我們要先宣告出一個int型別的變數:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Chapter16
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter an integer:");
            int myInt = Convert.ToInt32(Console.ReadLine());
        }
    }
}

 

 

STEP3:再來需要兩個bool型別的變數,以及判斷式:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Chapter16
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter an integer:");
            int myInt = Convert.ToInt32(Console.ReadLine());
            bool isLessThan10 = myInt < 10;
            bool isBetween0And5 = (0 <= myInt) && (myInt <= 5);
        }
    }
}

 

 

STEP4:接下來我們要將判斷的結果顯示出來,這個練習就完成嘍!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Chapter16
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Enter an integer:");
            int myInt = Convert.ToInt32(Console.ReadLine());
            bool isLessThan10 = myInt < 10;
            bool isBetween0And5 = (0 <= myInt) && (myInt <= 5);
            Console.WriteLine("Integer less than 10? {0}", isLessThan10);
            Console.WriteLine("Integer between 0 and 5? {0}", isBetween0And5);
            Console.WriteLine("Exactly one of the above is true? {0}", isLessThan10 ^ isBetween0And5);
            Console.ReadKey();
        }
    }
}

 

STEP5:執行看看,試著輸入一個整數(圖2),檢查判斷是否正確吧!(圖3)

ch16-01(圖2)

 

ch16-02(圖3)

 

小提醒:最後一個判斷是使用 ^ 運算子,因此除非前兩個判斷的結果,有一個是true,否則都是false,可以試著輸入不同的數值看看唷!

做完練習之後,對於這些運算子的運用有沒有更清楚了呢? 如果有時間的話,可以自己再多想幾個題目來試試看唷!

 

希望資深的前輩們與跟我一樣剛開始想學習C#的初心者,可以給我一些建議跟鼓勵,或是幫我在FB按個讚! 感謝您們 ~

 

(本文中相關內容有參閱、引述MSDN)

 

 

 

 

 

 


如果這篇文章對您有幫助,請幫我點選「我要推薦」、按個讚、或是幫我推到其他平台;您的鼓勵將會是我繼續努力的一大動力!!

若是有任何指教或是需要討論之處,也不用客氣,請在下面留言給我,我將會儘速回覆~

Share | . . . . . . . . . .