C#中无法隐式将int转换为ulong。

3
我用C#编写了以下代码,出现了“无法隐式转换类型ulong为int”的错误提示。我应该如何纠正这个错误?为什么会出现这种情况呢?
 Random rnd = new Random();

        ulong a;
        ulong input;
        int c1 = 0;
        int c2;  

        a = (ulong)rnd.Next(1, 101);

        Console.WriteLine("Welcome to the random number checker.\n" 
            +"You can guess the number. Try and find in how many tries you can get it right. "
            +"\n\t\t\t\tGame Start");

        do
        {
            Console.WriteLine("Enter your guess");
            input = Console.ReadLine();
            c1 = c1 + 1;
            c2 = c1 + 1;  
            if (input == a)
            {
                Console.WriteLine("CONGRATZ!!!!.You got that correct in "+c1
                    + "tries");
                c1 = c2;

            }
            else if (input > a)
            {
                Console.WriteLine("You guessed the number bit too high.try again ");
            }
            else
            {
                Console.WriteLine("You guessed the number bit too low ");
            };
        } while (c1 != c2);

每当我删除那个do {}部分,上面的程序就可以正常工作,但是一旦添加它,问题就出现了。

1
这行代码 input = Console.ReadLine(); 完全不应该编译通过;Console.ReadLine() 返回的是一个字符串 string,而不是无符号长整型 ulong - wablab
1
由于 ulong无符号 的,而 int有符号 的,因此如何转换 负数 值不清楚。你真的想要 ulong,而不是 long 吗? - Dmitry Bychenko
1
抱歉,我不相信您所展示的代码片段中会出现这种错误,因为没有将 ulong 赋值给 int 或类似操作。但是,您存在其他一些错误:Console.ReadLine() 返回的是 string 而不是 ulong,所以您不能将其赋值给 input - René Vogt
@Mats391 在哪里?我还是看不到。他只是将 ainput 比较,它们都是 ulong,将 c1c2 比较,它们都是 int - René Vogt
@RenéVogt 你是正确的。把 a 误认成了 c :| - Mats391
显示剩余2条评论
3个回答

2
今日免费次数已满, 请开通会员/明日再来
Cannot implicitly convert type 'string' to 'ulong'

在行内

input = Console.ReadLine();

如果您将其更改为以下内容,一切都会变得很好:

input = Convert.ToUInt64(Console.ReadLine());

0

Console.ReadLine(); 是问题所在。该方法返回一个 string,但是您的 input 被声明为 ulong。如果您希望用户输入数字值,则需要尝试解析它并在无法解析时报告错误。您可以像这样实现:

Console.WriteLine("Enter your guess");

            if (!ulong.TryParse(Console.ReadLine(), out input))
            {
                Console.WriteLine("Please enter numerical value");
                Environment.Exit(-1);
            }

0
问题出在这里:input = Console.ReadLine()ReadLine返回字符串,所以你不能将其保存为ulong类型。你应该这样做:
    ulong input;
    if (ulong.TryParse(Console.ReadLine(), out ulong)
    {
        input = input * 2;
    }
    else
    {
       Console.WriteLine("Invalid input!");
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接