C#while循环运行不一致

时间:2017-09-14 19:27:31

标签: c# for-loop while-loop

我有这段代码:

string winpath = Environment.GetEnvironmentVariable("C:");
int i = 0;

Console.WriteLine("How much would you like to destroy your pc?");

i = Convert.ToInt32(Console.ReadLine());
int j = 0;

while (j < i)
{
    Process.Start(winpath + @"\Windows\System32\calc.exe");
    j++;
}

我想让用户选择打开多少计算器,我输入1,得到一个计算器,输入2,我仍然得到一个计算器,输入3并得到一个计算器,输入5到2个计算器。我也尝试过for循环,但结果相同。

2 个答案:

答案 0 :(得分:2)

问题不在于循环,而是需要计算循环的最大值。 查看代码并根据您根据输入数量对所需的calc实例数进行描述,您需要使用整数除法:

i = Convert.ToInt32(Console.ReadLine());
int j = 0;
while (j < i / 2)
{
    ...
}

答案 1 :(得分:0)

您很可能需要在启动过程之间添加一个短暂的延迟。 while循环运行得如此之快,以至于Windows无法及时响应进程启动请求。

尝试在每个Process.Start()之后添加Thread.Sleep()

using System.Threading;

for (int i = 0; i < total; i++)
{
    Process.Start("calc.exe"); // anything in /system32 is already on the path
    Thread.Sleep(100); // 100 milliseconds
}