简体   繁体   English

为什么我的“while”循环没有结束? 是由于运算符优先级还是其他原因?

[英]Why is my 'while' loop not ending? Is it due to operator precedence, or anything else?

Why is my while loop not ending?为什么我的while循环没有结束? It is giving the correct result, but it runs in an infinite loop.它给出了正确的结果,但它在无限循环中运行。 Is it due to operator precedence?是因为运算符优先级吗?

void equate()
{
    int i = 0, n = 0;
    while (((a[i] != '\0') && (b[i] != '\0')) || (n != 1))
    {
        if (a[i] > b[i])
        {
            std::cout << "\n" << a << " string is greater";
            n = 1;
        }
        else if (a[i] < b[i])
        {
            std::cout << "\n" << b << " string is greater";
            n = 1;
        }
        else
            i++;
    }
    if (n == 0)
    {
        std::cout << "\n" << "Both strings " << a << " and " << b << " are equal";

    }

Within these if statements在这些 if 语句中

   if (a[i] > b[i])
   {
       std::cout << "\n" << a << " string is greater";
       n = 1;
   }
   else if (a[i] < b[i])
   {
       std::cout << "\n" << b << " string is greater";
       n = 1;
   }

the index i is not being incremented.索引i没有增加。 So the first subexpression in the condition of the while loop所以while循环条件中的第一个子表达式

((a[i] != '\0') && (b[i] != '\0'))

is always evaluates to true if the control was passed to these if statements.如果将控件传递给这些 if 语句,则 is 始终评估为 true。 As a result you will have an infinite loop.结果,您将有一个无限循环。

At least rewrite the condition like至少重写条件

while ( a[i] != '\0' && b[i] != '\0' && n != 1 )

Though the result of the loop (of the comparison of two strings) can be incorrect in the case when lengths of compared strings are unequal each other.尽管在比较字符串的长度彼此不相等的情况下,循环的结果(两个字符串的比较)可能是不正确的。

That is, it is not enough only to check whether n is equal to 0 as you are doing in this statement.也就是说,仅检查 n 是否等于 0 是不够的,就像您在此语句中所做的那样。

   if (n == 0)
   {
       std::cout << "\n" << "Both strings " << a << " and " << b << " are equal"; 
   }

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

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