C# - 随机数生成器错误



当我运行它并玩游戏时,每次只生成数字 0。你能帮我弄清楚问题是什么吗?

public partial class MainPage : PhoneApplicationPage
{
    int numberguessed;
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        Random randnum = new Random();
        int numberguessed = randnum.Next(0,1000);
    }

    private void myButton_Click(object sender, RoutedEventArgs e)
    {
        myTextBlock.Text = " No worries ! Go again .. ";
        myTextbox.Text = "";
        myTextbox.Focus();
    }
    private void myButton2_Click(object sender, RoutedEventArgs e)
    {
        //string sval = myTextbox.Text;
        int ival = System.Convert.ToInt32(myTextbox.Text);
        if (ival == numberguessed)
            myTextBlock.Text = " You won ";
        else if (ival < numberguessed)
            myTextBlock.Text = "Your guess is too low !";
        else if (ival > numberguessed)
            myTextBlock.Text = "Your guess is too high !";
    }
    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
    {
        myTextbox.Focus();
    }
在这一

部分中

public MainPage()
    {
        InitializeComponent();
        Random randnum = new Random();
        int numberguessed = randnum.Next(0,1000);
    }

您正在通过以"int"为前缀来覆盖顶级数字猜测变量。将其更改为:

public MainPage()
    {
        InitializeComponent();
        Random randnum = new Random();
        numberguessed = randnum.Next(0,1000);
    }

您将numberguessed声明为field,然后在 MainPage() 中重新声明一个新的局部变量int numberguessed。在其他方法中,将使用field值。由于它未初始化,因此它将具有 int 的默认值 0。

int numberguessed;
        // Constructor
        public MainPage()
        {
            InitializeComponent();
            Random randnum = new Random();
            //remove int there like this
            //int numberguessed = randnum.Next(0,1000);
           numberguessed = randnum.Next(0,1000);
        }

顺便说一下,你应该有一个警告(或者也许只是更锐利地这样做)说明

局部变量数字猜测隐藏字段。主页.数字猜测

更改此部分

int numberguessed;
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        Random randnum = new Random();
        int numberguessed = randnum.Next(0,1000);
    }

 private int numberguessed;
    // Constructor
    public MainPage()
    {
        InitializeComponent();
        Random randnum = new Random();
        numberguessed = randnum.Next(0,1000);
    }

问题是,一旦你在类中声明了你的字段/属性,然后在构造函数中再次创建一个类似的字段,并再次声明int numberguessed。后一个字段仅保留在构造函数内部的范围内,并在构造函数结束后消失。但是,所有 int 字段的默认值为 0,并且您正在访问的字段是在类外部定义的字段。因此,您只会获得默认值。

最新更新