Iterating until int.MaxValue reached

后端 未结 4 1793
無奈伤痛
無奈伤痛 2021-01-14 19:01

As a little test I wanted to see how long it would take to count to int.MaxValue in a C# console application. Every few hours I checked the progress. Last night when I thoug

相关标签:
4条回答
  • 2021-01-14 19:48

    Your for loop:

    for (int counter=0; counter <=numToCountTo ; counter++)
    

    is incorrect. It will execute while counter <= int.MaxValue which is ALWAYS true. When it increments it it will roll to int.MinValue and keep incrementing.

    Change it to

    for (int counter=0; counter < numToCountTo ; counter++)
    

    or use a long for your loop counter:

    for (long counter=0; counter <= numToCountTo ; counter++)
    

    You can also use a do...while loop since the loop is executed before the breaking condition is evaluated:

    int counter = 0;
    do
    {
       ...
       counter++;
    }
    while(counter < numToCountTo);
    
    0 讨论(0)
  • 2021-01-14 19:55

    It's called an overflow - the integer wraps around to the lowest possible negative value.

    If you want it to stop at maxInt you should replace the <= with a < - at present you can never stop the loop as counter can never be bigger can maxIni.

    0 讨论(0)
  • 2021-01-14 19:58

    When you add 1 to an Int32.MaxValue you will end up with Int32.MinValue.

    int a = Int32.MaxValue;
    a++; // a is now -2147483648
    
    0 讨论(0)
  • 2021-01-14 20:03

    It will continue because counter will never be > than int.MaxValue, if you do int.MaxValue+1 it will wrap down to int.MinValue.

    Thus, your for condition is always true.

    An alternative I would recommend is either use a larger datatype for your counter like long, or change your loop to:

    int counter = -1;
    for(;;) // while(true)
    {
        counter++;
        Console.WriteLine("{0}", counter);
    
        if (counter == int.MaxValue) 
        {
            break;
        } 
    }
    
    0 讨论(0)
提交回复
热议问题