c语言三元运算符_C中的三元运算符解释

c语言三元运算符

Programmers use the ternary operator for decision making in place of longer if and else conditional statements.

程序员使用三元运算符代替较长的ifelse条件语句进行决策。

The ternary operator take three arguments:

三元运算符采用三个参数:

  1. The first is a comparison argument

    第一个是比较参数
  2. The second is the result upon a true comparison

    第二是经过真正比较的结果
  3. The third is the result upon a false comparison

    第三是错误比较的结果

It helps to think of the ternary operator as a shorthand way or writing an if-else statement. Here’s a simple decision-making example using if and else:

将三元运算符视为简写方式或编写if-else语句会有所帮助。 这是一个使用ifelse的简单决策示例:

int a = 10, b = 20, c;

if (a < b) {
    c = a;
}
else {
    c = b;
}

printf("%d", c);

This example takes more than 10 lines, but that isn’t necessary. You can write the above program in just 3 lines of code using a ternary operator.

这个例子需要十行,但这不是必须的。 您可以使用三元运算符仅用3行代码编写以上程序。

句法 (Syntax)

condition ? value_if_true : value_if_false

condition ? value_if_true : value_if_false

The statement evaluates to value_if_true if condition is met, and value_if_false otherwise.

如果满足condition则该语句的值为value_if_true ,否则为value_if_false

Here’s the above example rewritten to use the ternary operator:

这是上面的示例重写为使用三元运算符:

int a = 10, b = 20, c;

c = (a < b) ? a : b;

printf("%d", c);

Output of the example above should be:

上面示例的输出应为:

10

c is set equal to a, because the condition a < b was true.

c设置为等于a ,因为条件a < b为真。

Remember that the arguments value_if_true and value_if_false must be of the same type, and they must be simple expressions rather than full statements.

请记住,参数value_if_truevalue_if_false必须具有相同的类型,并且它们必须是简单的表达式而不是完整的语句。

Ternary operators can be nested just like if-else statements. Consider the following code:

三元运算符可以像if-else语句一样嵌套。 考虑以下代码:

int a = 1, b = 2, ans;
if (a == 1) {
    if (b == 2) {
        ans = 3;
    } else {
        ans = 5;
    }
} else {
    ans = 0;
}
printf ("%d\n", ans);

Here's the code above rewritten using a nested ternary operator:

这是上面使用嵌套三元运算符重写的代码:

int a = 1, b = 2, ans;
ans = (a == 1 ? (b == 2 ? 3 : 5) : 0);
printf ("%d\n", ans);

The output of both sets of code above should be:

上面两组代码的输出应为:

3

翻译自: https://www.freecodecamp.org/news/c-ternary-operator/

c语言三元运算符

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值