三目运算符

•变量=(条件表达式)?(条件为真):(条件为假)
variable = (condition) ?expressionTrue : expressionFalse;

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#include <iostream> 
using namespace std; 
int main() { 
    int time; 
    char result; 
    cout<<"please input time: "; 
    cin>>time; 
    result = (time <12) ?'Y':'N'; 
    cout << result; 
    return 0; 
}

int a=10, b=20, z;
z =  (a>b) ? a : b;//条件成立赋左值z=a,条件不成立赋右值z=b
cout<<z;
int i = 1, j = 2, k = 3;
i == (i>j) ? (i = j + k, j = 5) : (k++, k++);
cout << i << ' ' << j << ' ' << k << endl;
Scroll to Top