1

私はC#コンソールでサイコロローラープログラムを書いています。私は2つの入力を与えています

  1. サイコロのサイズを入力し、
  2. プレイしたい時間を入力します。

サイコロのサイズが私がプレイした6倍と10倍だとします。

Output is coming:
1 was rolled  2 times
2 was rolled  7 times
3 was rolled  8 times
4 was rolled  7 times
5 was rolled  4 times
6 was rolled  5 times

合計:33(実行ごとに修正されるわけではありません。これは変更されません)

しかし、私の要件は、この合計は常にプレイ回数でなければならないということでした。ここで私は10回プレイしているので、合計は33ではなく10になるはずです。新しい数字ごとに発生するはずです... 100回プレイする場合、合計または合計は100で、他の数字だけではありません。残りはすべて同じままで、私のプログラミングでは期待される合計が得られません。誰かがそれを修正してください。これが私のコードです:

Dice.cs:

public class Dice
{
    Int32 _DiceSize;
    public  Int32 _NoOfDice;     
    public Dice(Int32 dicesize)
    {
        this._DiceSize = dicesize;         
    }
    public string Roll()
    {
        if (_DiceSize<= 0)
        {
            throw new ApplicationException("Dice Size cant be less than 0 or 0");                 
        }
        if (_NoOfDice <= 0)
        {
            throw new ApplicationException("No of dice cant be less than 0 or 0");
        }
        Random rnd = new Random();
        Int32[] roll = new Int32[_DiceSize];
        for (Int32 i = 0; i < _DiceSize; i++)
        {
            roll[i] = rnd.Next(1,_NoOfDice);
        }
        StringBuilder result = new StringBuilder();
        Int32 Total = 0;
        Console.WriteLine("Rolling.......");
        for (Int32 i = 0; i < roll.Length; i++)
        {
            Total += roll[i];
            result.AppendFormat("{0}:\t was rolled\t{1}\t times\n", i + 1, roll[i]);
        }
        result.AppendFormat("\t\t\t......\n");
        result.AppendFormat("TOTAL: {0}", Total);
        return result.ToString();
    }
}
class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine("Enter no of dice size");
        int dicesize = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("How many times want to play");
        int noofplay=Convert.ToInt32(Console.ReadLine());
        Dice obj = new Dice(dicesize);
        obj._NoOfDice = noofplay;
        obj.Roll();
        Console.WriteLine(obj.Roll());           
        Console.WriteLine("Press enter to exit");
        Console.ReadKey();
    }
}
4

4 に答える 4

5

数学を逆に取得しているように見えます...そうではありません:

// to capture just the counts
int[] roll = new int[_DiceSize];
for (int i = 0; i < _NoOfDice; i++)
{
    roll[rnd.Next(roll.Length)]++;
}

または、実際のロールが必要な場合:

// to capture individual rolls
int[] roll = new int[_NoOfDice];
for (int i = 0; i < _NoOfDice; i++)
{
    roll[i] = rnd.Next(_DiceSize) + 1; // note upper bound is exclusive, so +1
}
于 2009-07-27T08:13:39.690 に答える
2

Random各反復で新しいインスタンスを作成しています。これは、結果の均一な分布に影響を与えるため、良いことではありません。Random毎回新しいインスタンスを作成するのではなく、インスタンスをフィールドに保持します。

public class Dice {
    private Random rnd = new Random();

    // ... don't create a new random in `Roll` method. Use `rnd` directly.
}
于 2009-07-27T08:11:59.133 に答える