c# - 请求和存储用户输入 C#

标签 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();
    }
}

最佳答案

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

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

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

关于c# - 请求和存储用户输入 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49909867/

相关文章:

c# - 使用 Fluent NHibernate 覆盖 C# 属性访问器方法的基本行为

C 编程 - 调用 fgets() 两次?

Windows中的Python程序内存

c# - 为什么 System.Array 类实现 IList 但不提供 Add()

c# - 自定义文件属性

javascript - 通过 JavaScript 更改 HTML 表单 'input' 类型

c++ - getline 如何与 cin 一起工作?

c - 获取 Game Boy ROM 镜像

c - 使用 ansicon 在 Windows 7 控制台中使用 ANSI 颜色代码

c# - 我应该如何强制加载引用的程序集?