Iterating until int.MaxValue reached

2019-02-19 15:12发布

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 thought the program would be done executing, it was executing back to 0. I'm not sure why that happened and I was wondering if anyone could explain it to me. What it did was that it counted to 2,147,483,647 then when this value was reached it began counting backwards to zero. Even though it appeared to be counting backwards, the value had a negative number. I wonder if I needed to use the absolute value of int.MaxValue. Anyway, I was just curious if anyone could see what I'm not seeing. Here is my code. Thanks

static void Main(string[] args)
    {
        int maxInt = int.MaxValue;
        int numToCountTo = maxInt;
        //int numToCountTo = 1000000;

        try
        {
            Console.WriteLine(DateTime.Now);
            Console.WriteLine("Press any key to begin.");
            Console.ReadLine();

            Stopwatch sw = new Stopwatch();
            sw.Start();

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

                Console.WriteLine(counter);

            }


            sw.Stop();
            TimeSpan ts = sw.Elapsed;

            // Format and display the TimeSpan value.
            string elapsedTime = String.Format("{0:00 Hours}, {1:00 Minutes}, {2:00 Seconds}, {3:00 Milliseconds}",
                ts.Hours, ts.Minutes, ts.Seconds,
                ts.Milliseconds / 10);

            // ("#,#") places a comma between every 3 digits
            Console.WriteLine("It took " + elapsedTime + " to count to " + numToCountTo.ToString("#,#"));
            Console.WriteLine("Press Enter key to continue.");
            Console.ReadLine();
        }
        catch (Exception ex)
        { 
            throw new Exception("Exception Reached: " + ex.Message)
        }
    }

4条回答
Summer. ? 凉城
2楼-- · 2019-02-19 15:24

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

int a = Int32.MaxValue;
a++; // a is now -2147483648
查看更多
贼婆χ
3楼-- · 2019-02-19 15:26

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;
    } 
}
查看更多
欢心
4楼-- · 2019-02-19 15:31

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);
查看更多
萌系小妹纸
5楼-- · 2019-02-19 15:33

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.

查看更多
登录 后发表回答