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

时间:2017-02-08 15:38:14

标签: c#

我在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{}部分时,上层程序工作正常,但是当我添加它时显示出问题。

3 个答案:

答案 0 :(得分:0)

我编译你的代码只有一个错误:

Cannot implicitly convert type 'string' to 'ulong'

排队

input = Console.ReadLine();

如果您将其更改为:

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

一切都会好的

答案 1 :(得分:0)

input = 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);
            }

答案 2 :(得分:0)

问题在于:input = Console.ReadLine()ReadLine返回字符串,因此您无法将其保存为ulong类型。你应该这样做:

    ulong input;
    if (ulong.TryParse(Console.ReadLine(), out ulong)
    {
        input = input * 2;
    }
    else
    {
       Console.WriteLine("Invalid input!");
    }