【问题标题】:Ternary operator in while loopwhile循环中的三元运算符
【发布时间】:2022-01-04 04:03:23
【问题描述】:

在这种情况下,为什么 i 的输出是 1 而不是 0,因为 while 循环将 i 的值从原始值 i=2 减少了两倍?

#include<stdio.h>
int main(){
    int i=2,j=2;
    while(i+1?--i:j++)
         printf("%d",i);
    return 0;
}

【问题讨论】:

    标签: c while-loop conditional-operator


    【解决方案1】:

    这是因为你复杂的三元运算符可以简化为

    while(--i)
    

    解释。

    i+1 == 3, --i 执行。 i == 1 所以 while 循环的主体执行(打印 1)。现在i+1 == 2、--i 执行,i == 0 在 C 中为 false,并且正在跳过 while 循环的主体。

    i 减少了两次 - 但 printf 只执行了 1 次。

    你可以添加一个printf来测试它:

    int main(){
        int i=2,j=2;
        while(i+1?--i:j++)
             printf("%d\n",i);
        printf("%d\n",i);
        return 0;
    }
    

    结果会如预期的那样

    1
    0
    

    【讨论】:

      猜你喜欢
      • 2020-07-07
      • 1970-01-01
      • 2017-05-21
      • 1970-01-01
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      相关资源
      最近更新 更多