Sum the random data

Asked

Viewed 282 times

1

I have a code for a dice roller. Then the person will enter in the field the amount of data that will roll and after that the program will run the amount of data and add.

So I made a array to receive this data but I am not able to 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();
    }
}
  • 1

    You can comment line by line what your for should do? By the way, assemble the table test that will find the error quickly.

  • What’s the big deal? I do not know if you do what you want, but looking over I saw no mistake, except the fact that if someone enters something wrong will burst and have no value in array, what should be there?

2 answers

1


I think it should be 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();
 }

in no time did you value the qtd6[i] that I renamed to dados[i]

  • Thanks a lot, it worked out! I’m still learning the language and I haven’t practiced the logic for a long time.

  • Don’t forget to mark it as an answer! For nothing

1

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

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 neither would the loop need to be created. There will be a certain change of odds, but it can do so:

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

I put in the Github for future reference.

  • Hmm, thank you very much bigown. I will study this way, it seems to be much simpler even As I said I am learning now, so this is the way I found to solve the application.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.