我们在 C 中使用三元运算符,当条件为 true
时执行一段代码,当条件为 false
时执行另一段代码。例如:
(age >= 18) ? printf("Can Vote") : printf("Cannot Vote");
在这里,当 age 大于或等于 18 时,会打印 Can Vote
。否则,会打印 Cannot Vote
。
三元运算符的语法
三元运算符的语法是:
testCondition ? expression1 : expression 2;
testCondition
是一个布尔表达式,结果为 true 或 false。如果条件为
true
- 执行 expression1(冒号之前)false
- 执行 expression2(冒号之后)
三元运算符有 3 个操作数 (condition, expression1 和 expression2)
。因此,称为三元运算符。
示例:C 三元运算符
#include <stdio.h>
int main() {
int age;
// take input from users
printf("Enter your age: ");
scanf("%d", &age);
// ternary operator to find if a person can vote or not
(age >= 18) ? printf("You can vote") : printf("You cannot vote");
return 0;
}
输出 1
Enter your age: 12 You cannot vote
在上面的示例中,我们使用了三元运算符,它根据输入值检查用户是否可以投票。在这里,
age >= 18
- 测试条件,检查输入值是否大于或等于 18printf("You can vote")
- 如果条件为 true 则执行的 expression1printf("You cannot vote")
- 如果条件为 false 则执行的 expression2
这里,用户输入 12,所以条件变为 false。因此,我们得到 You cannot vote
作为输出。
输出 2
Enter your age: 24 You can vote
这一次输入值为 24,大于 18。因此,我们得到 You can vote
作为输出。
将三元运算符赋给变量
在 C 编程中,我们也可以将三元运算符的表达式赋给一个变量。例如:
variable = condition ? expression1 : expression2;
在这里,如果测试条件为 true
,则将 expression1 赋给变量。否则,将 expression2 赋给变量。
让我们看一个例子。
#include <stdio.h>
int main() {
// create variables
char operator = '+';
int num1 = 8;
int num2 = 7;
// using variables in ternary operator
int result = (operator == '+') ? (num1 + num2) : (num1 - num2);
printf("%d", result);
return 0;
}
// Output: 15
在上面的示例中,测试条件 (operator == '+')
始终为 true。因此,冒号前的第一个表达式,即两个整数 num1 和 num2 的和,被赋给了 result 变量。
最后,将 result 变量打印出来作为输出,显示 8 和 7 的和。即 15。
C 中的三元运算符与 if...else 语句
在某些情况下,我们可以用三元运算符替换 if...else
语句。这将使我们的代码更简洁、更短。
我们来看一个例子
#include <stdio.h>
int main() {
int number = 3;
if (number % 2 == 0) {
printf("Even Number");
}
else {
printf("Odd Number");
}
return 0;
}
我们可以用以下使用三元运算符的代码替换此代码。
#include <stdio.h>
int main() {
int number = 3;
(number % 2 == 0) ? printf("Even Number") : printf("Odd Number");
return 0;
}
这里,两个程序都在做相同的任务,即检查偶数/奇数。但是,使用三元运算符的代码看起来更简洁。
在这种情况下,当 if...else
块内只有一个语句时,我们可以用 ternary operator
替换它。
