【问题标题】:Method to return two random ints always returns the same one twice返回两个随机整数的方法总是两次返回相同的整数
【发布时间】:2012-08-26 17:24:39
【问题描述】:

我知道如何在 VB 中做到这一点,但我在 C# 中编码,所以我需要弄清楚如何获得两个不同的随机整数 (1 - 8),我似乎无法让它工作,我得到了同样的结果我越努力越努力。我已经阅读了很多,但我找不到更具体的帮助,因为大多数人只想要一个 rnd 号码,而我可以做到......简单;)

我编码的是这个,它没有给我两个不同的数字。

    public string GetFruitCombination()
    {
        Random fruitcombo = new Random();
        int indexone = fruitcombo.Next(0, 8);
        Random fruitcombotwo = new Random();
        int indextwo = fruitcombotwo.Next(0, 8);

        string firstfruit = m_fruit[indexone];
        string secondfruit = m_fruit[indextwo];

        return string.Format("{0}&{1}", firstfruit, secondfruit);
    }

必须有更简单的方法来获得 2 个不同的 rnd 数字,对吗?所以我需要有人把我推向正确的方向!

提前感谢您的任何想法和帮助!!!

//问候

【问题讨论】:

标签: c# random


【解决方案1】:

不要创建Random 的第二个实例,只需使用同一个实例两次。

(默认种子是基于时间的,因此在如此快速地创建两个种子时,它们很有可能拥有相同的种子。)

【讨论】:

  • 谢谢!!我快疯了:P
【解决方案2】:
   public string GetFruitCombination() 
    { 
        Random fruitcombo = new Random(Environment.TickCount); 
        int indexone = fruitcombo.Next(0, 8); 
        int indextwo = fruitcombo.Next(0, 8); 

        string firstfruit = m_fruit[indexone]; 
        string secondfruit = m_fruit[indextwo]; 

        return string.Format("{0}&{1}", firstfruit, secondfruit); 
    } 

虽然我个人使用的是 Random 的静态版本,所以种子是在启动时设置的,然后每次使用时只需 Nexted。 RNGCryptoServiceProvider 示例中还有一个更好的随机数HERE

【讨论】:

    猜你喜欢
    • 2019-02-20
    • 2016-10-14
    • 2017-05-20
    • 1970-01-01
    • 2016-10-29
    • 1970-01-01
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多