如何使用 C# 找出某個數字是否可以被 2 整除?


要找出某個數字是否能被 2 整除,就要找出當它被 2 整除時會發生什麼。

如果餘數為 0,則該數字可以被 2 整除,否則為假 −

if (num % 2 == 0) {
   Console.WriteLine("Divisible by 2 ");
} else {
   Console.WriteLine("Not divisible by 2");
}

以下為完整程式碼 −

示例

 互動演示

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

namespace Demo {
   class Test {
      static void Main(string[] args) {
         int num;
         num = 18;
         // checking if the number is divisible by 2 or not
         if (num % 2 == 0) {
            Console.WriteLine("Divisible by 2 ");
         } else {
            Console.WriteLine("Not divisible by 2");
         }
         Console.ReadLine();
      }
   }
}

輸出

Divisible by 2

更新於:2020-06-22

215 次瀏覽

職業生涯啟動計劃

完成課程獲得認證

開始學習
廣告
© . All rights reserved.