Random Number Generation in C# errors out

Refresh

5 days ago

Views

25 time

-3

So i am trying to generate a random number and if the number is 3 or 8 i what something to happen , it this case to add 1 to one of the 2 integers

keep in mind i really am only going off a book in C# and some knowledge in VB

    int Number1 = 0;
    int Number12 = 0;
    string text;
    string text2;

    Exexs:

    Random rnd = new Random();
    int month = rnd.Next(1, 10);

    if (month = 8)
    {
        Number1++;


    }
    else if (month = 3)
    {
        Number12++;
    }
    if (Number1 = 1)
    {
        text = "*";
    }


    goto Exexs;
}

}

2 answers

0

В C # для того , чтобы сравнить вам нужно использовать двойной = Таким образом, вместо того , чтобы :

if (month = 8)

тип:

if (month == 8)
1

Слишком много ошибок в коде; кажется, реализация должна быть что-то вроде этого:

int Number1 = 0;
int Number12 = 0;
// Do not forget to initialize the varaiables:
string text = "";
string text2 = "";

// Create (and initialize by system tomer) Random once, use many
Random rnd = new Random();

// Do not use goto, but loops (they are more readable: we have an infinite loop here)
while (true) {
  int month = rnd.Next(1, 10);

  // (month = 8) is an assignment, not comparison which is (month == 8)
  // C/C++ language trick: comparing in reversed order: 
  // (8 == month) and you can easily find out such errors
  if (8 == month)
    Number1++;
  else if (3 == month)
    Number12++;

  if (1 == Number1) {
    text = "*";

    // you want to leave the infinite loop (your current code never stops)
    break; 
  }
}

// Let's inspect the outcome
Console.Write($"Number1 = {Number1}; Number12 = {Number12} Text = {text}");