0

Trying to get 2 dice to roll 2 different numbers, but no matter what I try the 2 numbers are always the same. I can't work out why even after doing all this, the 2 numbers are always the same eg "6 and 6" "2 and 2".

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApplication7
{
    public partial class Form1 : Form
    {

        String[] rolldie()
        {
            int a = 0;
            int b = 0;
            string first = "";
            string second = "";
            for (int i=0; i<20; i++)
            {

                Random rnd = new Random();
                int dice = rnd.Next(1, 7);
                if (i == 0) { a = dice; }
                if (i == 10) { b = dice; }
                first = a.ToString();
                second = b.ToString();

            }
            string[] diceword = {first,second};
            return diceword;

        }

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            textBox1.Text = rolldie()[0];
            textBox2.Text = rolldie()[1];

        }
    }
}
percy
  • 27
  • 5
  • 2
    don't use a new random in each loop – Daniel A. White Jul 15 '16 at 20:47
  • dont create the random object in a loop. Create it once, perhaps in the ctor and just call Next() as needed – Ňɏssa Pøngjǣrdenlarp Jul 15 '16 at 20:47
  • you only call rnd.next() ONCE, so you only ever generate one random number per iteration. then a/b only get set/reset ONCE – Marc B Jul 15 '16 at 20:48
  • See 'remarks' section on documentation for `System.Random`. https://msdn.microsoft.com/en-us/library/system.random(v=vs.110).aspx#Anchor_4 It is a **psuedo** random generator, meaning it pretty much generates the same list of random numbers every time, and you keep creating new instances with the same seed value. – JamesFaix Jul 15 '16 at 20:50
  • Thanks, placing it outside the loop fixed the problem. – percy Jul 20 '16 at 16:43

0 Answers0