偶数是那些能被2整除的数字。
余数运算符
%
与数字一起使用时给出余数。例如,
const number = 6;
const result = number % 4; // 2
因此,当
%
与 2 一起使用时,如果余数为零,则数字为 偶数。否则,该数字为奇数。
示例 1: 使用 if...else
// program to check if the number is even or odd // take input from the user const number = prompt("Enter a number: "); //check if the number is even if(number % 2 == 0) { console.log("The number is even."); } // if the number is odd else { console.log("The number is odd."); }
输出
Enter a number: 27 The number is odd.
在上面的程序中,
number % 2 == 0
检查数字是否为偶数。如果余数为0,则数字为偶数。
在这种情况下,27 % 2 等于 1。因此,这个数字是奇数。
上述程序也可以使用三元运算符编写。
示例 2: 使用三元运算符
// program to check if the number is even or odd // take input from the user const number = prompt("Enter a number: "); // ternary operator const result = (number % 2 == 0) ? "even" : "odd"; // display the result console.log(`The number is ${result}.`);
输出
Enter a number: 5 The number is odd.