因此,我正在爲一個在1-100之間隨機生成的數字在猜謎遊戲中的學校項目工作。目前我唯一遇到的問題是,每當用戶輸入一個新號碼時,生成的號碼也會改變。我試着將代碼放在表單加載器中生成數字,但後來在程序中無法訪問它。這是迄今爲止我所擁有的。在c中的隨機數猜謎遊戲的麻煩#
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void guessButton_Click(object sender, EventArgs e)
{
int userGuess;
userGuess = int.Parse(guessText.Text);
Random rand = new Random();
int number = rand.Next(1, 100);
label2.Text = "" + number;
if (userGuess > number)
{
resultLabel.Text = "Your guess is too high";
}
else if (userGuess < number)
{
resultLabel.Text = "Your guess is too low.";
}
else if (userGuess == number)
{
resultLabel.Text = "That is correct!";
}
guessText.Clear();
}
private void exitButton_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
http://csharpindepth.com/Articles/Chapter12/Random.aspx – Oded 2014-10-11 19:11:15
形式裝載機在正確的位置把它。查找哪些字段和成員變量。 – 2014-10-11 19:13:15
@MobyDisk如果表單被關閉並打開,那麼隨機數仍然會每次都會重新生成。 – cybermonkey 2014-10-11 19:16:19