【问题标题】:Assigning an int using the ternary conditional operator and the values of two other ints使用三元条件运算符和其他两个 int 的值分配一个 int
【发布时间】:2014-09-11 04:07:51
【问题描述】:

在我用来学习 C 的 Big Nerd Ranch C 书中,它说“每当您遇到根据条件将值分配给变量的场景时,您就有一个候选 '条件/三元运算符',即?。”

所以我的问题是,有人可以向我解释以下代码 sn-p:

int i = 20;
int j = 25;
int k = (i > j) ? 10 : 5;

if (5 < j - k) {
    //First expression
    printf("the first expression is true.");
} else if ( j > i ) {
    //Second Expression 
    printf("The second expression is true.");
} else {
    printf("Neither expression is true.");
}

【问题讨论】:

  • k 等于 5,因为else if 行没有任何条件,所以不会编译。

标签: c if-statement ternary-operator conditional-operator


【解决方案1】:

您示例中的int k = (i &gt; j) ? 10 : 5; 相当于:

if (i > j)
{
    int k = 10;
}
else
{
    int k = 5;
}

三元运算符只是在根据条件分配值时 if 条件的特殊情况的快捷方式。

其余的sn-p并不难理解,如果去掉不完整的else ifsn-p:

if (5 < j(25) - k(5)) == if (5 < 20)
{
    printf("the expression is true.");
}
else
{
     printf("the expression is false.");
}

因为5小于25 - 5 = 20,所以这个程序会打印“第一个表达式为真”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-26
    • 2021-05-13
    • 1970-01-01
    • 2019-04-08
    • 2018-08-18
    • 1970-01-01
    • 2020-04-26
    相关资源
    最近更新 更多