C#Windows窗体应用程序 - Visual Studio
这是我的代码,它创建一个数组并按文本框中的数字值逐步对其进行排序。唯一的问题是,当我多次单击该按钮时,它会在实际数组和似乎是另一个随机数组之间切换。这是为什么?
int[] randArray = new int[5];
private void txtSeed_TextChanged(object sender, EventArgs e) {
int notaninteger;
if (!int.TryParse(txtSeed.Text, out notaninteger)) {
txtSeed.Text = "0";
}
if (int.Parse(txtSeed.Text) < 0) {
txtSeed.Text = "0";
}
}
private void btnLotto_Click(object sender, EventArgs e) {
fillArray();
sortArray();
showResult();
}
private void fillArray() {
bool inArray = true;
Random random = new Random(int.Parse(txtSeed.Text));
for (int i = 0; i < randArray.Length; i++) {
do {
int randomNumber = random.Next(1, 51);
inArray = checkArray(randomNumber);
if (!inArray) {
randArray[i] = randomNumber;
}
}
while (inArray);
}
}
private void displayArray() {
txtLotto.AppendText(getFormat());
txtLotto.AppendText("\r\n");
}
private void sortArray() {
txtLotto.Text = "";
for (int i = 0; i < randArray.Length; i++) {
for (int j = 0; j < randArray.Length - 1; j++) {
if (randArray[j] > randArray[j + 1]) {
swap(ref randArray[j], ref randArray[j + 1]);
displayArray();
}
}
}
}
private bool checkArray(int a) {
for (int i = 0; i < randArray.Length; i ++) {
if (randArray[i] == a) {
return true;
}
}
return false;
}
private string getFormat() {
string format = "";
for (int i = 0; i < randArray.Length; i ++) {
if (i != 0) {
format += "-";
}
format += randArray[i];
}
return format;
}
private void showResult() {
lblFinalResult.Text = "Final Result: ";
string format = "";
for (int i = 0; i < randArray.Length; i++) {
if (i != 0) {
format += "-";
}
format += randArray[i];
}
lblFinalResult.Text += format;
}
private void swap(ref int a, ref int b) {
int tempA = a;
a = b;
b = tempA;
}
答案 0 :(得分:0)
https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx
如果将相同的种子用于单独的随机对象,它们将会 生成相同系列的随机数。
你有2种不同类型的数组的原因是:
要解决您的问题,基本上规则只是创建一个Random实例并避免重新初始化(使用相同的种子)。因此,每次点击都会得到不同的数组。
private Random random = new Random(); // one instance of random
private int previousSeed = 0; // memorize previous seed
private void fillArray()
{
bool inArray = true;
int newSeed = int.Parse(txtSeed.Text);
if (newSeed != previousSeed)
{
// reinitialize the random only if new seed is different
random = new Random(newSeed);
previousSeed = newSeed;
}