If you want to get the largest of the two numbers, you can use the IF statement, for example:
if (a>b) {
max = A;
} else{
max = b;
}
However, the C language provides a simpler method, called the conditional operator, with the syntax format:
Expression of 1? Expression 2: Expression 3
The conditional operator is the only three-mesh operator in the C language whose evaluation rule is: If the value of the expression 1 is true, the value of the expression 2 is used as the value of the entire conditional expression, otherwise the value of the expression 3 is the value of the entire conditional expression. A conditional expression is usually used in an assignment statement.
The If Else statement above is equivalent to:
max = (a>b)? A:B;
The semantics of the statement is that, if A>b is true, A is given to Max, or B is given to Max. The reader can assume that the conditional operator is a shorthand if else, and can be replaced entirely with if else.
When you use conditional expressions, you should also note the following points:
1 The precedence of the conditional operator is lower than the relational and arithmetic operators, but is higher than the assignment character. So
max= (a>b)? A:B;
You can remove parentheses and write as
Max=a>b? A:B;
2 The conditional operator? And: is a pair of operators that cannot be used separately.
3 The binding direction of the conditional operator is from right to left. For example:
A>b? A:c>d? C:d;
Should be understood as:
A>b? A: (C>d c:d);
This is the case where the conditional expression is nested, where the expression is a conditional expression.
To reprogram with a conditional expression to output the maximum value of two digits:
#include <stdio.h>
int main () {
int A, b;
printf ("Input two numbers:");
scanf ("%d%d", &a, &b);
printf ("max=%d\n", a>b?a:b);
return 0;
}
Run Result:
Input two numbers:23 45
Max=45
The above is the C language conditional operator knowledge of the explanation, the need for friends can refer to.