我想生成一個1到10之間的隨機數。但是我收到了一些錯誤。C#生成隨機數
public Form1()
{
InitializeComponent();
}
int randomNumber = (0, 11);
int attempts = 0;
public int RandomNumber
{
get
{
return randomNumber;
}
set
{
randomNumber = value;
}
}
它是所有在0,11逗號下是說 - >結構System.Int32表示32位有符號整數< - 。在11下它說 - >標識符預期的語法錯誤,','預計< - 。現在,如果我只是像int randomNumber = 0;那麼它會正常工作,仍然有多次猜測,並且猜測數量會像它應該加起來一樣,並且標籤太高太低。只是數字將永遠是0.
另外我怎樣才能使它到我沒有點擊猜測按鈕,我可以打在鍵盤上輸入?
private void button1_Click_1(object sender, EventArgs e)
{
try
{
if (int.Parse(textBox1.Text) > RandomNumber) label1.Text = "Too high.";
else if (int.Parse(textBox1.Text) < RandomNumber) label1.Text = "Too low.";
else
{
label1.Text = "You won.";
textBox1.Enabled = false;
label2.Text = "Attempts: 0";
textBox1.Text = String.Empty;
MessageBox.Show("You won in " + attempts + " attempts, press generate to play again.", "Winner!");
attempts = 0;
label2.Text = "Attempts: " + attempts.ToString();
return;
}
attempts++;
label2.Text = "Attempts: " + attempts.ToString();
}
catch { MessageBox.Show("Please enter a number."); }
}
C#沒有用於生成隨機數的特殊語法。如果你想產生一個隨機數,看看'隨機'類。 – Luaan
http://stackoverflow.com/questions/2706500/how-do-i-generate-a-random-int-number-in-c – daremachine
你可以在這裏找到答案:http://stackoverflow.com/questions/ 2706500 /我怎麼生成一個隨機-int-number-in-c – Breeze