如何使用 C# 查詢數字是否可以被 2 整除?


查詢數字是否可以被 2 整除,檢查當數字可以被 2 整除時會發生什麼。

如果餘數為 0,則數字可以被 2 整除,否則為 false —

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.