c# - 如何在 C# 中读取用户的十进制数?

标签 c#

所以我是编程新手 3 周,我正在尝试使用 C# 制作一个基本的控制台计算器。我不知道如何从用户那里读取小数点(例如 5.5)。正常的整数(例如5)可以工作。我收到以下异常错误:

An unhandled exception of type 'System.FormatException' occurred in mscorlib.dll

Additional information: Input string was not in a correct format.

这是代码:

Console.WriteLine(
  "Hi there, My name is Mohammed.\n" +
  "Today we are going to be doing several calculations.\n\n" +
  "These would include Addition, Subtraction, Multiplication and Division. ");

Console.WriteLine("To get started, please hit the space key.");
Console.ReadKey();

Console.WriteLine("We will start with a addition. Please enter the first number.");
double num01 = Convert.ToDouble(Console.ReadLine());

Console.WriteLine("Now enter the second number");
double num02 = Convert.ToDouble(Console.ReadLine());

double ans01 = (num01 + num02);
Console.WriteLine(num01 + "+" + num02 + " is equals to " + ans01 + 
    "\nGreat, now lets move on to subtraction. Please enter the first number.");

最佳答案

我建议方法提取,像这样:

using System.Globalization;

...

private static double ReadDouble(string title)
{
    while (true) 
    {
        Console.WriteLine(title);

        string userInput = Console.ReadLine();

        double result;

        // We use CultureInfo.InvariantCulture to ensure that
        // decimal separator is dot (.). i.e. we expect 5.5 input
        if (double.TryParse(userInput, 
                            NumberStyles.Any, 
                            CultureInfo.InvariantCulture, 
                            out result))
        {
            return result;
        }

        Console.WriteLine("Sorry, incorrect format. Enter it again, please.");  
    }
}

然后我们就可以使用例程了

...
Console.ReadKey();

double num01 = ReadDouble("We will start with a addition. Please enter the first number.");

double num02 = ReadDouble("Now enter the second number");

double ans01 = (num01 + num02);
...

关于c# - 如何在 C# 中读取用户的十进制数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46117794/

相关文章:

c# - listbox selectionmode = multiextended 如何摆脱按下鼠标键选择项目

c# - 函数中绝对数的总和

c# - 振动直到消息框关闭 Windows Phone 7

c# - AUTOINCREMENT 不适用于 OleDbCommand

c# - 如何始终在小数点后显示 3 个数字#

c# - 编辑表单中的 Asp.net mvc 计算字段

c# - C#如何处理内存

c# - 对标准标识符命名感到困惑

c# - 使用 EntityState.Modified 时出错

c# - 在使用 Entity Fluent API 映射的 View 中使用 ROW_NUMBER 设置主键会使 linq 超时