简体   繁体   English

if语句中的条件为小数时

[英]When condition inside if statement is fractional

void main(void)
{
    int i;
    for(i=1;i<=5;i++)
    {
        if(i/5)
            continue;
        printf("%d",i);
    }
}

My simple query is,if the condition inside "if" is evaluated to a fraction,is it treated as 0?As here the output is 1234,so when condition is 1/5,2/5,3/5,4/5 it is prinnting values of i,when 5/5=1 it is executing continue statement. 我的简单查询是,如果将“ if”中的条件评估为分数,是否将其视为0?这里的输出为1234,所以当条件为1 / 5,2 / 5,3 / 5,4 / 5时它是i的打印值,当5/5 = 1时,它正在执行Continue语句。

i/5 will be treated as integer division (when i is int of course), no matter where it appears in ( if or whatever). i/5将被视为整数除法(当iint当然),无论它出现在( if或其他)。 So / between two integers will actually give you the quotient. 因此,两个整数之间的/实际上会给您商。

i / 5 will give 0 when i ∈ {0, 1, 2, 3, 4} and 1 when i = 5 . i ∈ {0, 1, 2, 3, 4}i / 5将给出0 i ∈ {0, 1, 2, 3, 4}而当i = 5i ∈ {0, 1, 2, 3, 4}将给出1

The if statement executes the conditional statement (in this case the continue statement ) when its conditional expression is true . if条件语句为trueif语句执行条件语句(在本例中为continue语句)。 An integer value is casted to boolean as follows: zero becomes false , any other value becomes true . 如下将整数值转换为布尔值:零变为false ,其他任何值变为true Since the expression does not evaluate to a non-zero value until i==5 , the conditional statement is not executed until then. 由于表达式在i==5之前不会求值为非零值,因此直到那时才执行条件语句。

Whenever you have 每当你有

if ( expr )

and the expr isn't obviously something that's true/false, you can always think of it like this: 而且expr显然不是对/错的东西,您总可以这样认为:

if( (expr) != 0)

So if the expr evaluates to something fractional, well, as long as the fraction is not equal to 0, the condition will evaluate as true. 因此,如果expr计算为分数,那么只要分数不等于0,该条件就将计算为true。

However, in your example, since i is an integer, i/5 will do integer division which will never give a fraction. 但是,在您的示例中,由于i是整数,所以i/5将执行整数除法,该运算将永远不会给出分数。 And if i is less than 5, i/5 will be 0, which will end up making the conditional false. 如果i小于5,则i/5将为0,这将使条件为假。

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

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