Iterating until int.MaxValue reached

后端 未结 4 1792
無奈伤痛
無奈伤痛 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);
    

提交回复
热议问题