如何使用 C# 找出某個數字是否可以被 2 整除?
要找出某個數字是否能被 2 整除,就要找出當它被 2 整除時會發生什麼。
如果餘數為 0,則該數字可以被 2 整除,否則為假 −
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
安卓
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP