简体   繁体   English

C ++:While循环不会中断

[英]C++: While Loop won't break

we just had an exercise at school and one part of it is to check, if a given EAN (European Article Number) is valid. 我们刚刚在学校进行过一次练习,其中一部分是检查给定的EAN(欧洲商品编号)是否有效。

I wrote a function for it, but when I am using the while-loop, it won't go out of the loop. 我为此编写了一个函数,但是当我使用while循环时,它不会脱离循环。 Here's the code: 这是代码:

bool checkEan13(unsigned int code[])
{
    int sum1 = 0;
    int sum2 = 0;
    int sum;

    for (int i = 0; i <= 10; i += 2)
    {
        sum1 += code[i];
    }

    for (int i = 1; i <= 11; i += 2)
    {
        sum2 += code[i];
    }

    sum2 *= 3;
    sum = sum1 + sum2;

    int difference;
    int nextNumber = sum;

    while (!nextNumber % 10 == 0)
    {
        nextNumber++;

        //if (nextNumber % 10 == 0)        <-- it works, when I put in this
        //{                                <--
        //  break;                         <--
        //}                                <--
    }

    difference = nextNumber - sum;

    if (difference == code[12])
    {
        return true;
    }
    else {
        return false;
    }
}

As you can see in the code, it works, when I do a check with an if-statement, but why does it not work without it? 如您在代码中所见,当我使用if语句进行检查时,它可以工作,但是为什么没有它就不能工作? Shouldn't the statement of the while-loop be invaild, if "nextNumber" is eg 50? 如果“ nextNumber”为例如50,是否不应调用while循环的语句?

Thanks! 谢谢!

This has to do with operator precedence . 这与运算符优先级有关 ! has a higher precedence then % so your condition is actually evaluated as 优先级高于%因此您的病情实际上被评估为

(!nextNumber) % 10 == 0

So if nextNumber is a non 0 value then (!nextNumber) if false or 0 and 0 % 10 is 0 因此,如果nextNumber为非0值,则为(!nextNumber)如果为false或0且0 % 10为0

To fix it you can use 要修复它,您可以使用

!(nextNumber % 10 == 0)

Which will check if nextNumber % 10 is equal to 0 and return the opposite of that check. 它将检查nextNumber % 10是否等于0并返回与该检查相反的结果。

Of course as Marc van Leeuwen pointed out we could simply write 当然,正如Marc van Leeuwen所指出的,我们可以简单地写

nextNumber % 10 != 0

which does the exact same things and now we no longer have to worry about the operator precedence. 它执行完全相同的操作,现在我们不再需要担心运算符的优先级。

Please read about operator precedence. 请阅读有关运算符优先级的信息。 Try with while (!((nextNumber%10)==0)) . 试试while (!((nextNumber%10)==0))

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

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