原文: https://www.programiz.com/cpp-programming/examples/even-odd
要理解此示例,您应该了解以下 C++ 编程主题:
完全可以被 2 整除的整数称为偶数。
那些不能被 2 整除的整数不称为奇数。
为了检查整数是偶数还是奇数,使用模数运算符%将整数除以 2 时将计算出余数。 如果余数为零,则该整数为偶数,即使不是整数也为奇数。
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter an integer: ";
cin >> n;
if ( n % 2 == 0)
cout << n << " is even.";
else
cout << n << " is odd.";
return 0;
} 输出
Enter an integer: 23
23 is odd.在此程序中,if..else语句用于检查n%2 == 0是否为true。 如果该表达式为真,则n为偶数,即使n不为奇数。
您也可以使用三元运算符?:代替if..else语句。 三元运算符是if...else语句的简写形式。
#include <iostream>
using namespace std;
int main()
{
int n;
cout << "Enter an integer: ";
cin >> n;
(n % 2 == 0) ? cout << n << " is even." : cout << n << " is odd.";
return 0;
}