C 语言中的三元运算符
C 语言中的三元运算符 (?:) 是一种条件运算符。"三元"一词表示该运算符有三个操作数。三元运算符通常用于以更紧凑的方式组合多个条件 (if-else) 语句。
C 语言中三元运算符的语法
三元运算符的语法如下:
exp1 ? exp2 : exp3
它使用三个操作数:
- exp1 - 布尔表达式,结果为 true 或 false
- exp2 - 由 ? 返回当 exp1 为真时,? 运算符返回的值。
- exp3 − 当 exp1 为假时,? 运算符返回的值。
示例 1:C 语言中的三元运算符
以下 C 程序使用三元运算符检查变量的值是偶数还是奇数。
#include <stdio.h> int main(){ int a = 10; (a % 2 == 0) ? printf("%d is Even ", a) : printf("%d is Odd ", a); return 0; }
输出
运行此代码时,将产生以下输出 -
10 is Even
将"a"的值改为 15,然后再次运行代码。现在您将获得以下输出 -
15 is Odd
示例 2
条件运算符是 ifelse 结构的简洁表示。我们可以通过以下代码重写检查奇数/偶数的逻辑 -
#include <stdio.h> int main(){ int a = 10; if (a % 2 == 0){ printf("%d is Even ", a); } else{ printf("%d is Odd ", a); } return 0; }
输出
运行代码并检查其输出 −
10 is Even
示例 3
以下程序比较两个变量"a"和"b",并将较大的值赋给变量"c"。
#include <stdio.h> int main(){ int a = 100, b = 20, c; c = (a >= b) ? a : b; printf ("a: %d b: %d c: %d ", a, b, c); return 0; }
输出
运行此代码时,将产生以下输出 -
a: 100 b: 20 c: 100
示例 4
使用 ifelse 结构对应的代码如下 -
#include <stdio.h> int main(){ int a = 100, b = 20, c; if (a >= b){ c = a; } else { c = b; } printf ("a: %d b: %d c: %d ", a, b, c); return 0; }
输出
运行代码并检查其输出 −
a: 100 b: 20 c: 100
示例 5
如果需要在三元运算符的 true 和/或 false 操作数中放置多个语句,则必须用逗号分隔它们,如下所示 -
#include <stdio.h> int main(){ int a = 100, b = 20, c; c = (a >= b) ? printf ("a is larger "), c = a : printf("b is larger "), c = b; printf ("a: %d b: %d c: %d ", a, b, c); return 0; }
输出
在此代码中,将较大的数字赋给"c",并打印相应的消息。
a is larger a: 100 b: 20 c: 20
示例 6
使用 ifelse 语句的相应程序如下 -
#include <stdio.h> int main(){ int a = 100, b = 20, c; if(a >= b){ printf("a is larger "); c = a; } else{ printf("b is larger "); c = b; } printf ("a: %d b: %d c: %d ", a, b, c); return 0; }
输出
运行代码并检查其输出 −
a is larger a: 100 b: 20 c: 100
嵌套三元运算符
就像使用嵌套的 if-else 语句一样,我们可以在 True 操作数和 False 操作数中使用三元运算符。
exp1 ? (exp2 ? expr3 : expr4) : (exp5 ? expr6: expr7)
首先,C 语言检查 expr1 是否为真。如果是,则检查 expr2。如果为真,则结果为 expr3;如果为假,则结果为 expr4。
如果 expr1 为假,它可能会检查 expr5 是否为真,并返回 expr6 或 expr7。
示例 1
让我们开发一个 C 程序来确定一个数字是否能被 2 和 3 整除,或者能被 2 但不能被 3 整除,或者能被 3 但不能被 2 整除,或者既不能被 2 整除又不能被 3 整除。我们将使用嵌套条件运算符来实现此目的,如以下代码所示 -
#include <stdio.h> int main(){ int a = 15; printf("a: %d ", a); (a % 2 == 0) ? ( (a%3 == 0)? printf("divisible by 2 and 3") : printf("divisible by 2 but not 3")) : ( (a%3 == 0)? printf("divisible by 3 but not 2") : printf("not divisible by 2, not divisible by 3") ); return 0; }
输出
检查不同的值 −
a: 15 divisible by 3 but not 2 a: 16 divisible by 2 but not 3 a: 17 not divisible by 2, not divisible by 3 a: 18 divisible by 2 and 3
示例 2
在此程序中,我们使用嵌套的 ifelse 语句代替条件运算符来达到相同的目的 -
#include <stdio.h> int main(){ int a = 15; printf("a: %d ", a); if(a % 2 == 0){ if (a % 3 == 0){ printf("divisible by 2 and 3"); } else { printf("divisible by 2 but not 3"); } } else{ if(a % 3 == 0){ printf("divisible by 3 but not 2"); } else { printf("not divisible by 2, not divisible by 3"); } } return 0; }
输出
运行此代码时,将产生以下输出 -
a: 15 divisible by 3 but not 2