简体   繁体   中英

how to set up random number generation without remainder?

how can I set my generator random number for division to list only numbers which, when divided, had no remainder? I need only single digit number.

I tried:

 Random druhy = new Random();
            Random prvni = new Random();
            
            int maxprvni = 10;
            int maxdruhy = 10;
            
            int prvnic = prvni.Next(1, maxprvni);
            int druhyc = druhy.Next(2, maxdruhy);
...
if (znamenko.Text == "/")
            {
                int zbytek = (prvnic % druhyc);
                if (zbytek == 0)
                {
                    int total = (prvnic / druhyc);
                    prvnit.Text = prvnic.ToString();
                    druhyt.Text = druhyc.ToString();
                    vysledek.Text = total.ToString();
                }

            }

this will not write any number to my calculator because it has a numeric remainder.

What I could write in ELSE to generate another number, and so on until the number was completely?

Rather than generating a random number to divide, you could generate a random multiple of the divisor.

// Generate a random divisor, which could be anything except 0
int druhyc = druhy.Next(2, maxdruhy);

// Generate a random multiple of `druhyc`
// Ensure that it does not exceed maxprvni
int prvnic = druhyc * prvni.Next(1, maxprvni / druhyc);

// The division now has no remainder:
int total = (prvnic / druhyc);

By dividing maxprvni / druhyc , it ensures that the random number generated will not exceed maxprvni when multiplied by druhyc .

Working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM