编写一个 C# 程序来检查一个数字是否能被 2 整除
csharpprogrammingserver side programming更新于 2025/10/15 19:52:17
要检查一个数字是否能被 2 整除,首先需要求出它的余数。
如果一个数字除以 2 后的余数为 0,那么它就能被 2 整除。
假设我们的数字是 10,我们将使用以下 if-else − 语句来检查它。
// 检查该数字是否能被 2 整除
if (num % 2 == 0) {
Console.WriteLine("Divisible by 2");
} else {
Console.WriteLine("Not divisible by 2");
}
以下示例用于判断数字是否能被 2 整除 −
示例
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Demo {
class MyApplication {
static void Main(string[] args) {
int num;
num = 10;
// 检查数字是否能被 2 整除
if (num % 2 == 0) {
Console.WriteLine("能被 2 整除");
} else {
Console.WriteLine("不能被 2 整除");
}
Console.ReadLine();
}
}
}
输出
能被 2 整除

