具有相同值的变量 [英] variables with same value

查看:75
本文介绍了具有相同值的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编码的新手,我在使用这段代码时遇到了一些麻烦。

当我运行程序时,玩家的名字和分数对于两个玩家都是一样的但是我调试时有所不同。这是为什么?



I''m new to coding and I''m having some troubles with this piece of code.
Players'' name and score are the same for both players when I run the program but different when I debug. Why is that?

private string name;
private int ID;
private static int nextID = 1;
private int score;

public void Test()
{
    Player player1 = new Player();
    player1.Register();
    player1.SetRandomInfo();
    Console.WriteLine(InfoToString(player1));

    Player player2 = new Player();
    player2.Register();
    player2.SetRandomInfo();
    Console.WriteLine(InfoToString(player2));
}

public void SetRandomInfo()
{
    Random randomGen = new Random();
    int random = randomGen.Next(100);
    name = "player" + random;
    random = randomGen.Next(20);
    score = random;
}

推荐答案

每次调用SetRandomInfo()方法时都不应初始化randomGen变量。



更好地创建一个类范围的随机变量,在类的构造函数中初始化它(使用种子或不使用种子),并在您的方法中使用它。 />


名称 ID 得分变量应该是本地变量,相反。
You should not initialize your randomGen variable each time you call the SetRandomInfo() method.

Better create a class-wide Random variable, initialize it in the constructor of the class (with a seed or not), and use it in your method.

Name, ID and score variables should be local ones, on the contrary.


你好,



尝试提供随机数生成器的初始种子值。例如

Hello,

Try providing the initial seed value to the Random Number Generator. e.g.
DrandomGen = new Random((int) DateTime.Now.Ticks & 0x0000FFFF);



问候,


Regards,


这篇关于具有相同值的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆