代码只能通过将其与步进调试运行时,正确的? [英] Code runs correctly only when stepping through it with debugger?
问题描述
可能重复:结果
的随机数生成器只生成一个随机数
我就有点这个几分钟前百思不得其解。我有以下代码:
I was a bit baffled with this few moments ago. I have the following code:
public blockType generateRandomBlock()
{
Random random = new Random();
int makeBlockOfType = random.Next(0, 100);
blockType t = blockType.normal;
if (makeBlockOfType <= 80 && makeBlockOfType >= 60)
{
t = blockType.blue;
}
else if (makeBlockOfType > 80 && makeBlockOfType <= 95)
{
t = blockType.orange;
}
else if (makeBlockOfType > 95 && makeBlockOfType <= 100)
{
t = blockType.green;
}
return t;
}
相当简单,它返回一个枚举
基于随机生成的数字值(根据系统时间)。不幸的是,一些奇怪的原因,我有所有的块不是一种颜色或即使这会运行的每一个块被放进游戏中的其他。然而,当我通过这个步骤与调试器,然后看到一些运行后的结果,我看到的块多,现在根据所提供的机会着色。我有点搞不清楚为什么这种情况正在发生。
Fairly simple, it return an enum
value based on a randomly generated number (based of system time). Unfortunately for some odd reason, I have all blocks either one color or the other even though this runs for every single block being put into the game. However, when I step through this with the debugger and then see the results after some run, I see that the blocks are now multi colored based on the chances provided. I am a little bit confused about why this is happening.
有关这个我使用MonoGame它使用单声道编译器替代微软之一。难道这是问题?我试图内嵌把这段代码到构造函数从它被调用的地方,但我得到了同样的结果(我猜编译器反正内联的代码)。
For this I am using MonoGame which uses the Mono compiler instead of the Microsoft one. Could this be the issue? I have tried to put this code inline into the constructor from where it is being called but I am getting the same result (I am guessing the compiler inlines the code anyways).
我试图重新启动Visual Studio它分开,而不是让运行做构建;没有变化。
I have tried to restart Visual Studio it separately rather than letting the run do the build; no changes.
任何建议和帮助是非常感谢!
Any suggestions and help are greatly appreciated!
推荐答案
你应该实例化随机只有一次(将其设置为在构造私有字段和实例化),看到类似的问题:的 Random.Next总是返回相同的值
You should instanciate Random only once (set it as a private field and instanciate in the constructor), see the similar question : Random.Next returns always the same values
见的随机文档:
从随机数生成启动种子值。如果同一
种子反复使用,会产生同样的一串数字。
The random number generation starts from a seed value. If the same seed is used repeatedly, the same series of numbers is generated
在你的情况,你创建一个随机例如使用相同的种子(时间太近),你拿这将是一个给定的种子相同的第一个值。
In your case, you create a Random instance with the same seed (too close in time) and you take the first value which will be the same for a given seed.
这篇关于代码只能通过将其与步进调试运行时,正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!