所以我是编程新手 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/