2017-09-14 76 views
0

我有这样的代码:C#不一致

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

始终使用'Path.Combine'到Concat的你的路径字符串。 – LarsTech

+0

另外,System32将会在搜索路径中,所以你只需要'Process.Start(“calc.exe”)'。 –

+1

那么你的实际问题是什么?您的代码与您的要求不符,但您不会说什么是“不一致”。 – slugster

回答

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 
} 
+0

这工作,虽然我用了1000毫秒的延迟,谢谢。 – Oliver

2

你的问题不是循环,而是你需要计算循环的最大值。在你的代码 展望,并根据您的多少计算的情况下,要根据所输入的数字说明,你需要使用整数除法:

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