Console.Read()没有捕获正确的信息

本文关键字:信息 Read Console | 更新日期: 2023-09-27 18:06:33

我正在运行一个非常简单的程序,它只是提示用户输入一个数字,现在只是将它打印在屏幕上。但是由于某种我不知道的原因,我输入的数字似乎加到了数字48上。

例如

:输入2然后输出50

是我在监督某种基本规律,还是我在代码中犯了某种错误?

我是初学者,如果你没有注意到

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int Num;
            Console.WriteLine("Please Input Number of Rows you want to make in your pyrimid: ");
            Num = Console.Read();
            Console.WriteLine(Num);// Just to check if it is getting the right number
            Console.Read();//This is Here just so the console window doesn't close when the program runs
        }
    }
}

编辑:讨厌成为一个麻烦,但现在得到这个错误的num = int.Parse(Console.Read());为'int.Parse(string)'的最佳重载方法匹配有一些无效的参数。这是否意味着我需要一个重载方法?

Console.Read()没有捕获正确的信息

Console.Read返回char,因此当您将其转换为int时,您将获得2的ASCII码,这是50!您应该将其解析为int而不是(隐式)强制转换:

Num = int.Parse(Console.Read());

指出:

  1. 如果输入可以是非数值,则使用int.TryParse
  2. c#中对局部变量的约定是camelCase,因此将Num更改为num

Console.Read返回字符代码,而不是字符本身。

char num = (char)Console.Read();
Console.WriteLine(int.Parse(num.ToString()));

这段代码并不理想,但它显示了正在发生的事情。因为你希望输入一个数字,你也可以使用

int num = Console.Read() - 48;

Console.Read read从标准输入读取字节

2的ASCII值为50

您需要解析从控制台

读取的值
Num = Int32.Parse(Console.Read()); // or Num = int.Parse(Console.Read());