如何使用 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.