作为一个小测试,我想看看在 C# 控制台应用程序中计数到 int.MaxValue 需要多长时间。每隔几个小时,我就会检查一下进度。昨晚当我认为程序将执行完毕时,它正在执行回 0。我不确定为什么会发生这种情况,我想知道是否有人可以向我解释。它所做的是它计数到 2,147,483,647,然后当达到这个值时,它开始倒数到零。尽管它看起来是倒数,但该值是负数。我想知道是否需要使用 int.MaxValue 的绝对值。无论如何,我只是好奇是否有人能看到我没有看到的东西。这是我的代码。谢谢
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)
}
}