介紹C++中的「條件運算子」(Conditional operator),它的使用方式如下:
條件式 ? 成立傳回值 : 失敗傳回值


條件運算子的傳回值依條件式的結果而定,如果條件式的結果為true,則傳回冒號前的值,若為false,則傳回冒號後的值,下面這個程式可以作個簡單的示範:

#include <iostream>
using namespace std;
 
int main() {
    int score = 0;

    cout << "輸入學生分數:";
    cin >> score;
    cout << "該生是否及格?"
         << (score >= 60 ? 'Y' : 'N')
         << endl;

    return 0;
}

ex2:

#include <iostream>
using namespace std;

int main() {
int input = 0;

cout << "輸入整數:";
cin >> input;
cout << "該數為奇數?"
<< (input%2 ? 'Y' : 'N')
<< endl;

return 0;
}
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 風箏 的頭像
    風箏

    風箏

    風箏 發表在 痞客邦 留言(0) 人氣()