How to randomly choose + and - to calculate?
int a = (10 / 2) тут 10 Start with this:
if Random(2) = 0 then ..плюс.. else ..минус.. Continue like this:
a = (10 / 2) + 10 * (Random(2) * 2 - 1) * language is not C #, but I hope the essence is clear
If the question is how to randomly choose an operator (addition or subtraction), then the following method will do:
Random random = new Random(); int a = 10 / 2; // первоначальное значение if (random.Next(0, 2) == 0) a += 10; // прибавить какое-то значение else a -= 10; // отнять какое-то значение Or, if the same expression is added / taken away, it can be more cunning:
Random random = new Random(); int a = 10 / 2; // первоначальное значение a += (random.Next(0, 2) == 0 ? 1 : -1) * 10; // выражение в половине случаев будет умножаться на -1, а только затем прибавляться Method 1.
var rnd = new Random(DateTime.Now.Second); Func<int> rndSign = () => (int)Math.Pow(-1, rnd.Next(1, 3)); Method 2
Func<int> rndSign = () => rnd.Next() == 1 ? 1 : -1; var a = (10 / 2) + rndSign() * 10; Source: https://ru.stackoverflow.com/questions/826555/
All Articles