要确定数字是否被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