请求和存储用户输入c#

时间:2018-04-18 22:21:14

标签: c# input console

所以这看起来有点傻,但我试图创建一个程序,接受用户的两个x,y,z坐标并确定它们之间的距离。但是,运行此选项会跳过行并提供随机数。我是c#的新手,非常感谢任何帮助!

namespace CoordinateCalcMC
{
  class Program
{
    static void Main(string[] args)
    {
        int X1;
        int Y1;
        int Z1;
        int X2;
        int Y2;
        int Z2;
        int XDist;
        int YDist;
        int ZDist;
        int TotalDist;

        Console.WriteLine("Please enter the X coordinate of the first point.");
        X1 = Console.Read();
        Console.WriteLine("Please enter the Y coordinate of the first point.");
        Y1 = Console.Read();
        Console.WriteLine("Please enter the Z coordinate of the first point.");
        Z1 = Console.Read();
        Console.WriteLine("Your first point is " + X1 + ", " + Y1 + ", " + Z1 + ".");
        Console.WriteLine("Please enter the X coordinate of the second point.");
        X2 = Console.Read();
        Console.WriteLine("Please enter the Y coordinate of the second point.");
        Y2 = Console.Read();
        Console.WriteLine("Please enter the Z coordinate of the second point.");
        Z2 = Console.Read();
        Console.WriteLine("Your second point is " + X2 + ", " + Y2 + ", " + Z2 + ".");
        XDist = Math.Abs(X1 - X2);
        YDist = Math.Abs(Y1 - Y2);
        ZDist = Math.Abs(Z1 - Z2);
        TotalDist = XDist + YDist + ZDist;
        Console.WriteLine("The total X distance is " + XDist + ".");
        Console.WriteLine("The total Y distance is " + YDist + ".");
        Console.WriteLine("The total Z distance is " + ZDist + ".");
        Console.WriteLine("The total number of rails needed to connect these two points is: " + TotalDist);
        Console.Read();
    }
}

}

1 个答案:

答案 0 :(得分:3)

Console.Read从控制台读取单个字符。当您将值赋给int时,您实际上获得了字符的ASCII值(例如,如果用户输入" 1"则根据asciitable.com,该值将为49)。

您需要读入一行输入,并将输入解析为整数,如下所示:

X1 = int.Parse(Console.ReadLine());