Self C ++ (iv) // ternary operator

Ternary operator:

Read the following code:
IF (A> B)
Z = A;
the else
Z = B;
the code can be simplified toz=(a>b)?a:b;
z = (a> b) a:? b; the formula 3 is a conditional expression with the operation target, wherein the? : Add operator called three mesh y

Ternary operator priority: the execution direction from right to left:

z = (a> b) a: b; equivalent to z = a> b a:?? (a> b a: b?)

Ternary operator is typed questions:

Here Insert Picture Description
Code:

#include<iostream>
using namespace std;
int main()
{
	int a=1;
	float b=1.41;
	cout<<(a>b?a:b)<<endl;
	return 0;
}

Enter the result:
Here Insert Picture Description

Ternary operator in the use of character variables:

#include<iostream>
using namespace std;
int main()
{
	char a;
	cin>>a;
	cout<<(a=(a>='A'&&a<='Z')?(a+32):a)<<endl;
	return 0;
}

Here Insert Picture Description

Published 63 original articles · won praise 12 · views 4086

Guess you like

Origin blog.csdn.net/qq_45353823/article/details/100059990