代码在调试时工作,但在运行时却没有。 [英] Code works in debug but not when I run it.
问题描述
我是一名初学者并且正在使用控制台应用程序。
Hi,I am a beginner and playing around with a console application.
我有这个代码:
重点是调用一个创建随机数的方法,然后将值发送到并插入我的数组。
The point is to call a method which creates random numbers and send the value to and poulate my array.
问题是这在调试模式下工作,但在运行应用程序时却不行。
The problem is that this works in debug mode but not when I run the application.
为什么会这样,我该如何解决?
Why is this and how should I solve it?
public static int Random()
{
随机randomerare = new Random();
int randomNum = randomerare.Next(1,26);
return randomNum;
}
static void Main(string [] args)
{
int [] RNumbers = new int [7];
for(int x = 0; x< RNumbers.Length; x ++)
{
RNumbers [x] = Random();
}
public static int Random()
{
Random randomerare = new Random();
int randomNum = randomerare.Next(1, 26);
return randomNum;
}
static void Main(string[] args)
{
int[] RNumbers = new int[7];
for (int x = 0; x < RNumbers.Length; x++)
{
RNumbers[x] = Random();
}
推荐答案
要修复它,只需移动线
To fix it, just move the line
随机randomerare = new Random( );
Random randomerare = new Random();
在包含它的方法之外,以便在类级别定义。
outside of the method that contains it, so that it is defined at class level.
这样你只使用一个实例随机类,而不是为每个随机数创建一个新实例。如果您创建一个新实例,它将从系统时钟初始化,并且在运行时 循环非常快,以至于它在
之前运行,时钟已经改变了一个滴答,因此您始终将随机数生成器重置为生成相同的初始数字。
In this way you only use a single instance of the random class, rather than creating a new instance for each random number. If you create a new instance, it is initialized from the system clock, and at runtime the loop is so fast that it runs before the clock has changed a single tick, so you always reset the random number generator to generate the same initial number.
这篇关于代码在调试时工作,但在运行时却没有。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!