【问题标题】:C# variable is not the value I want [duplicate]C# 变量不是我想要的值[重复]
【发布时间】:2020-12-30 16:55:33
【问题描述】:

这是我的代码,我是 C# 的初学者,但习惯使用 python,我的问题是当用户输入他们的答案时,变量 answer 会将用户输入的内容添加到 48。我不知道数据 48 来自哪里from 但如果用户输入 2 那么它将使 answer = 50。

Random numGen = new Random(); //importing random
int score = 0; //setting a variable

for (int i = 0; i < 10; i++)  //for loop repeating 10 times
{ 
    int num1 = numGen.Next(1, 11); // random number between 1 and 10
    int num2 = numGen.Next(1, 11);
    Console.WriteLine("What is " + num1 + " mutliplied by " + num2 + "? "); 
    //asking a multiplication question
    int answer = 0;
    answer = Console.Read(); //input answer
    int result = num1 * num2; 
    if (result == answer) //checking answer is correct
    {
        Console.WriteLine("Well done that is correct!");
        score = score + 1;
    }
    else 
    {
        Console.WriteLine("Unlucky that was incorrect");
    }
    Console.WriteLine("Press enter for the next question");
    Console.ReadKey();  //waits before closing
}

【问题讨论】:

  • Console.Read 不会返回您认为的 - 它返回一个字符代码
  • '2' 的 ASCII 值为 50。

标签: c# variables


【解决方案1】:

answer = Console.Read(); 读取一个字符。该字符由一个 ascii 数字表示。

由于48 = '0' - 50 = '2' 等等,该值似乎是正确的。

您需要使用:Int32.Parse(Console.ReadLine()); 来获得预期的输出。

最好使用Int32.TryParse 风格来确保在用户输入非数字输入时不会出现运行时异常。

int answer = 0;
Int32.TryParse(Console.ReadLine(), out answer);

【讨论】:

    【解决方案2】:

    根据the documentationConsole.Read只返回字符,不返回数字。您应该考虑改用Console.ReadLineint.TryParse

    【讨论】:

      【解决方案3】:

      改变这一行:

      answer = Console.Read(); //input answer
      

      到这个:

      int.TryParse(Console.ReadLine(),out answer)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-07-20
        • 1970-01-01
        • 1970-01-01
        • 2014-11-30
        相关资源
        最近更新 更多