问题
I used double.Parse
and Convert.ToDouble
and got the same error
System.FormatException: Input string was not in a correct format.
When I write in console 10.2
or any other double number.
I learnt from a tutorial and I followed it step by step but I have no idea how to solve this.
Also I am using Visual Studio.
Console.WriteLine("Enter a number: ");
double num1 = double.Parse(Console.ReadLine());
Console.Write("Enter operator: ");
string op = Console.ReadLine();
Console.WriteLine("Enter a number: ");
double num2 = double.Parse(Console.ReadLine());
if (op == "+")
{
Console.Write(num1 + num2);
}
else if (op == "-")
{
Console.WriteLine(num1 - num2);
}
else if (op == "/")
{
Console.WriteLine(num1 / num2);
}
else if (op == "*")
{
Console.WriteLine(num1 * num2);
}
else
{
Console.WriteLine("Invalid Operator");
}
回答1:
The problem might be your culutral setting.
Some countries uses a .
others uses a ,
try:
double num2 = double.Parse(Console.ReadLine(), NumberStyles.Any, CultureInfo.InvariantCulture);
or set the separator like:
var culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.NumberFormat.NumberDecimalSeparator = ".";
double num2 = DateTime.Parse(Console.ReadLine(), culture);
来源:https://stackoverflow.com/questions/60372540/how-to-convert-console-readline-to-double-in-simple-calculator-c-sharp-probl