C++ 实例 - 判断一个数是奇数还是偶数

以下我们使用 % 来判断一个数是奇数还是偶数,原理是,将这个数除于 2 如果余数为 0 为偶数,否则为奇数。

实例 - 使用 if...else

#include <bits/stdc++.h>
using namespace std;
 
int main() {
  
    int n;
    cin >> n;
 
    if ( n % 2 == 0)
        cout << n << " 为偶数。";
    else
        cout << n << " 为奇数。";
 
    return 0;
}

以上程序执行输出结果为:

5
5 为奇数。

实例 - 使用三元运算符

#include <bits/stdc++.h>
using namespace std;
 
int main() {
    int n;
    cin >> n;
    
    (n % 2 == 0) ? cout << n << "  为偶数。" :  cout << n << " 为奇数。";
    
    return 0;
}

以上程序执行输出结果为:

5
5 为奇数。