首页 > 解决方案 > C# 代码问题 - 代码无法正常工作

问题描述

我用 C# 写了一个基本的猜数字游戏。无论用户选择什么 var c ,似乎每次都会返回第三个选项(“错误的选择!请重试。”)。我正在尝试使用字符(s 而不是 1 和 w 而不是 2 等,用 c 作为字符串),但它给出了相同的结果。不知道哪里不好。

using System;

namespace Challanges
{
    class Program
    {
        static int guess = 500;
        static int low = 1;
        static int high = 1000;
        static bool cont = false;


        static void Guess() //guesses and adjusts variables according to input.
        {
            int c;
            Console.WriteLine("Is your number greater or less than: " + guess + Environment.NewLine + "If it is less than, press 1; if it is greater, press 2." + Environment.NewLine + "If it is your number, press 3.");
            c = Convert.ToInt32(Console.Read());

            if (c == 1)
            {
                high = 500;
                guess = low + high / 2;
            }
            else if (c == 2)
            {
                low = 500;
                guess = low + high / 2;
            }
            else if (c == 3)
            {
                Console.WriteLine("Congratulations!! We found your number!");
                cont = true;
            }
            else
            {
                Console.WriteLine("Wrong choice! Please try again.");
                Console.ReadKey();
            }
        }

        static void Main(string[] args)
        {


            Console.WriteLine("Hello World!" + Environment.NewLine + "Let's play a guessing game. Think of a number between 1 and 1000." + Environment.NewLine + "Type your number :)");
            int x = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Your number is: " + x + Environment.NewLine + "Too easy?");
            Console.ReadKey();
            Console.WriteLine("Think of a number");
            if(cont == false)
            {
                Guess();

            } else
            {
                Console.ReadKey();
            }

        }
    }
}

标签: c#debugging

解决方案


正如之前的评论中提到的,Console.Read()返回一个字符代码。数字 1 的字符代码是 49,因此您的条件失败并执行 else 块。

你想要做的是使用Console.ReadLine()它返回一个字符串而不是字符代码。如果您将其string转换为,Int32您应该能够正确评估您的条件。


推荐阅读