简体   繁体   English

三元运算符

[英]C ternary operator

While studying CI faced something that is completely confusing my mind. 在学习CI的过程中,我完全感到困惑。

The expression is: 表达式是:

exp(V*log(i))?i%2?s:s--:s++;

If ternary operator is Question?Positive:Negative; 如果三元运算符是Question?Positive:Negative; I thought it was something like: 我以为是这样的:

if(pow(i,V)==1&&(i%2)==0)
    s--;
 else
    s++;

However, the s does not enter in the question, should I ask what does the first expression mean? 但是, s没有输入问题,请问第一个表达式是什么意思?

The program worked perfectly, but I could not understand why. 该程序运行良好,但我不明白为什么。

The original program is: 原始程序是:

main(){
    #define V 1

    int a, s=0, i;
    for(i=1000;i>=0;i--)
        exp(V*log(i))?i%2?s:s--:s++;
    exp(V*log(i))?printf("%d\t%d\t",-s,i):printf("%d\t%d\t", s,-i);
    getch();
}

如果exp(V log(i))为true,则测试是否为奇数i%2 == 1,如果返回s,甚至返回s-如果exp(V log(i))为false,返回s ++如果编写像这样比看起来容易:

exp(V*log(i))?(i%2?s:s--):s++;

The ternary operator tests if an expression is true. 三元运算符测试表达式是否为真。 To understand this case you need to analyse it and separate the two uses of the operator: 要了解这种情况,您需要对其进行分析并将操作符的两种用法分开:

exp(V*log(i))?i%2?s:s--:s++;

This translates to 这转化为

if(exp(V*log(i))
    if(i%2)
       s;
    else
       s--;
else
    s++;

The only difference is that it is an expression and a single statement instead of the if / else version. 唯一的区别是它是一个表达式和一个语句,而不是if / else版本。 It always returns the current value of s but changes it depending on the condition. 它总是返回s的当前值,但会根据条件进行更改。

If exp refers to the exponential function, then unless the output is -inf the output will be !=0 so the value will evaluate to true . 如果exp指代指数函数,那么除非输出为-inf ,否则输出将为!=0因此该值将计算为true Note that nan will also evaluate to false and nan is the output for log when the value is outside its domain. 请注意,当值超出其域时, nan还将求值为false,并且nanlog的输出。

So basically you could translate this with a much simpler expression (unless V is zero, the value for i==0 would change): 因此,基本上,您可以使用更简单的表达式对此进行翻译(除非V为零,否则i==0的值将发生变化):

i>0?s++:i%2?s:s--;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM