Add the random data

1

I have a code for a data roller. Then the person will type in the field the amount of data that will roll and after that the program will rotate the amount of data and add up.

Then I made an array to receive this data but I can not add them ...

Random rnd = new Random();

int dado6lado;

private void button1_Click(object sender, EventArgs e)
{
    int d6 = Convert.ToInt32(qtdD6.Text);
    int[] qtd6 = new int[d6];
    int soma = 0;

    //aqui a função vai pegar a quantidade de dados em qtd6.Lenght, rolar e somar na variavel soma e após isso exibir o valor na ultima linha
    for (int i = 0; i < qtd6.Length; i++ ) {
         //Dado
         dado6lados = rnd.Next(1, 7);

         soma = dado6lados + qtd6[i] ;

         resultadoD6.Text = soma.ToString();
    }
}
    
asked by anonymous 07.07.2017 / 23:48

2 answers

0

I think it should look like this:

Random rnd = new Random();

int dado6lado;

private void button1_Click(object sender, EventArgs e)
{
    int d6 = Convert.ToInt32(qtdD6.Text);
    int[] dados = new int[d6];
    int soma = 0;

    for (int i = 0; i < dados.Length; i++ ) {
        dados[i] = rnd.Next(1, 7);
        soma += dados[i];
    }

    resultadoD6.Text = soma.ToString();
 }

At no time did you assign value to qtd6[i] which I renamed to dados[i]

    
07.07.2017 / 23:59
1

The question is a bit confusing, but given the accepted answer has a very simple way to solve this. The array has no function in this algorithm, so just kill it. Too variable too:

int soma = 0;
for (int i = 0; i < Convert.ToInt32(qtdD6.Text); i++) {
    soma += rnd.Next(1, 7);
}
resultadoD6.Text = soma.ToString();

This has a problem. If someone enters something invalid to convert to number will break the application. The more correct would be to use a TryParse() .

It's not exactly the same thing, but even the bond would not have to be created. There will be a certain change of probabilities, but you can do this:

var qtde = Convert.ToInt32(qtdD6.Text)
resultadoD6.Text = (rnd.Next(qtde, qtde * 6 + 1)).ToString();

I placed GitHub for future reference .

    
08.07.2017 / 22:03