随机最小值不能大于最大值

Random minvalue cannot be greater than maxvalue

我正在尝试制作一个基于控制台的应用程序,其中程序将从用户提供的范围中减去两个随机数,但是当我输入值时,它会给我一个“随机最小值不能大于最大值”错误

这是我的代码

static void subtract()
        {

            bool tryagain = true;
            while (tryagain == true)
            {
                Console.WriteLine("Choose a range of numbers");

                Console.Write("First Value: ");
                int firstval = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("First value: " + firstval);

                Console.WriteLine("Second Value: ");
                int secondval = Convert.ToInt32(Console.ReadLine());
                Console.WriteLine("Second value: " + secondval);
          
                Console.WriteLine(firstval + secondval);
                Random rnd = new Random();
                int firstrndval = rnd.Next(firstval, secondval); //this line is throwing the error
                int secondrndval = rnd.Next(firstval, secondval);
                Console.WriteLine("What is " + firstrndval + "-" + secondrndval);

                int potans;
                potans = Convert.ToInt32(Console.ReadLine());

                int ans = firstrndval - secondrndval;
                if (ans != potans)
                {
                    Console.WriteLine("Wrong Answer");
                }
                else
                {
                    Console.WriteLine("Correct Answer");
                }
                Console.WriteLine("Would you like to try again Y/N");
                string potbol = Console.ReadLine();

                potbol = potbol.ToUpper();

                if (potbol == "N")
                {
                    tryagain = false;
                }
            }
        }

如果 firstval 小于 secondval,我尝试切换值,但它不起作用,我尝试了元组方法和三变量方法,但它似乎对我不起作用,可能是因为它在 if-else 中statement.I我对 C# 还很陌生,似乎无法解决这个问题。

你有两个选择
第一个:如果第一个数大于第二个数,交换他们这样

            if (firstval > secondval)
            {
                int temp = firstval;
                firstval = secondval;
                secondval = temp;
            }

这将确保 firstVal 始终是较大的
第二种解决方案像这样使用Math.Min() & Math.Max()函数

int firstrndval = rnd.Next(Math.Min(firstval, secondval), Math.Max(firstval, secondval));
int secondrndval = rnd.Next(Math.Min(firstval, secondval), Math.Max(firstval, secondval));

这将确保两个变量的最小值首先是 firstVal 或 SecondVal,并且两个变量的最大值相同

首先你必须找出两者中较小的数和较大的数:

int smaller = Math.Min(firstval, secondval);
int biggest = Math.Max(firstval, secondval);

int firstrndval = rnd.Next(smaller, biggest + 1);
int secondrndval = rnd.Next(smaller, biggest + 1);

您必须在第二个参数上加上 +1,因为第二个参数是独占的。这意味着,如果您输入 rnd.Next(1,10),它只会在 {1,2,3,4,5,6,7,8,9} 中显示 return 个数字(永远不会是 10)。