C#输出与断点输出不同 [英] C# output different from breakpoint output
问题描述
一个函数使用for循环将24个随机字符串从数组输入到字符串列表中.另一个功能在控制台中显示列表中的字符串.但是,我只得到一个循环的值,例如1111111111111111111111111111.设置断点时,得到的是我一直在寻找的输出,例如12kingace342356110.这是我的函数类代码.
One function inputs 24 random strings into an string list from an array with a for loop. The other function displays the strings from the list in the console. However I get only one value looped for example like 1111111111111111111111111. When I set breakpoint, I get the output I was looking for such as 12kingace342356110. Here's my function class code.
namespace CardWarConsoleGame
{
class Deck
{
public string[] CardNames = { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" };
public int[] CardValues = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
}
class WarFunctions
{
public static List<string> YourDeck = new List<string>();
public static List<string> AIDeck = new List<string>();
public static void LoadCards()
{
Deck deck = new Deck();
for (int i = 0; i < 24; i++)
{
Random r = new Random();
YourDeck.Add(deck.CardNames[r.Next(0, 14)]);
}
}
public static void test()
{
for (int i = 0; i < YourDeck.Count; i++)
{
Console.Write(YourDeck[i]);
}
}
}
}
Heres the program.cs
namespace CardWarConsoleGame
{
class Program : WarFunctions
{
static void Main(string[] args)
{
LoadCards();
test();
Console.ReadLine();
}
}
}
推荐答案
您应在循环之前创建Random
.
public static void LoadCards()
{
Deck deck = new Deck();
Random r = new Random();
for (int i = 0; i < 24; i++)
{
YourDeck.Add(deck.CardNames[r.Next(0, 14)]);
}
}
使用时间相关的默认种子值初始化Random类的新实例.
Initializes a new instance of the Random class, using a time-dependent default seed value.
默认种子值是从系统时钟派生的,并且具有有限的分辨率.结果,通过调用默认构造函数紧密连续创建的不同Random对象将具有相同的默认种子值,因此将产生相同的随机数集.
The default seed value is derived from the system clock and has finite resolution. As a result, different Random objects that are created in close succession by a call to the default constructor will have identical default seed values and, therefore, will produce identical sets of random numbers.
这篇关于C#输出与断点输出不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!