C# - 随机数生成器错误

时间:2013-09-13 08:53:24

标签: 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();
    }

3 个答案:

答案 0 :(得分:4)

在这部分

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);
    }

答案 1 :(得分:4)

您将numberguessed声明为field,然后在int numberguessed中重新声明新的本地变量MainPage()。在其他方法中,将使用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);
        }

顺便说一句,你应该发出一个警告(或者它可能只是重塑它),说明

  

本地变量编号隐藏字段.MainPage.numberguessed

答案 2 :(得分:0)

更改此部分

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,您正在访问的字段是在类外部定义的字段。因此,您只获得默认值。