开发者

Non-terminating while loop

开发者 https://www.devze.com 2023-03-16 22:57 出处:网络
I was just wondering something. I have the following code: #include <iostream> using namespace std;

I was just wondering something. I have the following code:

#include <iostream>
using namespace std;

int main()
{
    int number, largest, counter = 1;
    while (counter <= 10)
    {
          cout << "Enter a number: ";
          cin >> number;
          if (counter = 1)
          {
               largest = number;
          }
          else if (number > largest)
          {
               largest = number;
              }
          counter++;
    }
    cout << "\n\nThe largest number is: " << largest;
    system("pause");
    return 0;
} 

The thing is, it never terminates. I did manage to fix the problem by modifying the code a little, but I was wondering why this happened. Here is the fixed code:

#include <iostream>
using namespace std;

int main()
{
    int number, largest, counter = 1;
    cout << "Enter a number: ";
    cin >> number;
    largest = number;
    while (counter < 10)
    {
      cout << "Enter a number: ";
      cin >> number;
      if (number > largest)
      {
           largest = number;
      }
      counter++;
    }
    cout << "\n\nThe largest number is: " << largest <开发者_开发百科< endl;
    system("pause");
    return 0;
}

It seems that after removing the else if statement it worked. What happened?


if (counter = 1) 

this should be

if (counter == 1) 

otherwise, you're going to reset your counter to 1 each iteration.


if (counter = 1) reassigns 1 to counter every loop this being always < 10.

You want if (counter == 1).


A common mistake:

if( counter = 1) // assignment operator

This will set counter's value to 1 at each iteration, and the loop never finishes.

You should use

if( counter == 1) // equality operator
           ^^^^

which is exactly what you mean


  if (counter = 1)

This does not compare counter and 1, it assigns 1 to counter and then checks counter- which we just set to 1 so it will always be positive and always be <= 10.


The line

if (counter = 1)

Should be

if (counter == 1)

since you want to compare, not to assign value.


Your first example had

if (counter = 1)

instead of

if (counter == 1)

so the if statement would reset counter to 1 during each iteration.


Your problem is here:

if (counter = 1)

Assignment instead of comparison. Compile with higher warning level.


if (counter = 1)

So, counter value is 1 forever.


You're assigning 1 to counter rather than comparing it, use == instead of =


As other notice, this is a common error. Your could avoid it by typing

if( 1 == counter )

instead of

if( counter == 1 )

since

if( 1 = counter )

would not compile (if you made the error and forgot an '=').

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号