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

csharpprogrammingserver side programming更新于 2025/5/26 9:07:17

要查找数字是否可以被 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;
         // 检查数字是否可以被 2 整除
         if (num % 2 == 0) {
            Console.WriteLine("Divisible by 2 ");
         } else {
            Console.WriteLine("Not divisible by 2");
         }
         Console.ReadLine();
      }
   }
}

输出

Divisible by 2

相关文章