【问题标题】:I wanna make a random math questions and I can't do more then 18 numbers at the answer [duplicate]我想做一个随机的数学问题,我不能做超过 18 个数字的答案 [重复]
【发布时间】:2019-06-30 12:08:48
【问题描述】:
public static void Main(string[] args)
    {
        Random numberGen = new Random();

        int num01 = numberGen.Next(1,1000001);
        int num02 = numberGen.Next(1,1000001);

        Console.WriteLine("What is " + num01 + " times " + num02 + " ?");

        int Answer = Convert.ToInt32(Console.ReadLine());
        if (Answer == num01 * num02)
        {
            Console.WriteLine("Well done your correct!");
        } 
        else
        {
            int responseIndex2 = numberGen.Next(1, 3);
            switch (responseIndex2) {

                case 1:
                    Console.WriteLine("You noob");
                    break;
                case 2:
                    Console.WriteLine("Are you trying uh?!");
                    break;
            }

        }

        Console.ReadKey();
    }

好的,所以我找不到 Convert.ToInt32 的任何替代品,当我尝试运行程序时,当我回答时它崩溃了,我认为它是因为它的数字太多,即使它只有 20 个数字?

【问题讨论】:

  • 你的意思是数字不是数字,对吧?如果这就是您的意思,请改用long Answer = Convert.ToInt64(Console.ReadLine());
  • its crashes 始终清楚异常是什么,在哪一行。
  • 尝试对 100 个唯一数字进行排序: Random rand = new Random(); int[] numbers = Enumerable.Range(0, 100).ToArray(); int[] randomNumbers = numbers.Select(x => new { number = x, rand = rand.Next() }).OrderBy(x => x.rand).Select(x => x.number).ToArray( );

标签: c#


【解决方案1】:

一个 32 位有符号整数 (int) 可以存储的最大值为 2^31 - 1,它小于你的随机数学问题可以有的最大答案(最大答案是 1000001 * 1000001,大约10^12)。

因此,您不应使用int 来存储答案。您可以改用longlong 是一个 64 位的单数整数,其最大值为 2^63 - 1,大约为 9*10^18,远远大于你的数学问题所能得到的最大答案。

可以使用对应的Convert.ToInt64将字符串转换为long

long Answer = Convert.ToInt64(Console.ReadLine());
if (Answer == (long)num01 * (long)num02)
{
    Console.WriteLine("Well done your correct!");
} 
else
{
    int responseIndex2 = numberGen.Next(1, 3);
    switch (responseIndex2) {

        case 1:
            Console.WriteLine("You noob");
            break;
        case 2:
            Console.WriteLine("Are you trying uh?!");
            break;
    }

}

【讨论】:

    猜你喜欢
    • 2022-07-20
    • 1970-01-01
    • 2020-12-02
    • 1970-01-01
    • 2018-01-27
    • 2011-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多