输入字符串的格式不正确-URI 1116



我的代码中有一个问题无法解决:

输入字符串的格式不正确。

我不能在平台的在线编译器上运行它,这正是我需要使用它的地方。

using System;
public class help {
public static void Main() {
int n = Int32.Parse(Console.ReadLine());
for (int i = 0; i < n; i++) 
{
string[] line = Console.ReadLine().Split(' ');
double X = double.Parse(line[0]);
double Y = double.Parse(line[1]);
if (Y == 0) {
Console.WriteLine("divisao impossivel");
} else {
double divisao = X / Y; // Digite aqui o calculo da divisao
Console.WriteLine(divisao.ToString("F1"));
}
}
}
}

有什么想法吗?

您没有说明错误发生的位置。如果输入一个非整数字符,然后尝试将其解析为整数,则会出现错误System.FormatException: Input string was not in a correct format,同样使用double。请改用TryParse

你的程序没有提供任何说明,所以不清楚应该输入什么。

尝试以下操作:

static void Main(string[] args)
{
int n = 0;
Console.WriteLine("nWelcome. This program will divide two double values and display the result.");
Console.WriteLine("To exit the program, type 'exit'n");
do
{
Console.Write("Enter two double values, seperated by a space (ex: 2.2 10.4) or type 'exit' to quit the program. : ");
string line = Console.ReadLine();
if (line.ToLower().Trim() == "exit" || line.ToLower().Trim() == "quit")
{
Console.WriteLine("nExiting. Hope you enjoyed using the program.");
break; //exit loop
}
if (!String.IsNullOrEmpty(line))
{
double X = 0;
double Y = 0;
//trim leading and trailing spaces, then split on space
string[] userInputArr = line.Trim().Split(' ');
if (userInputArr != null && userInputArr.Length == 2)
{
//try to parse user input
Double.TryParse(userInputArr[0], out X);
Double.TryParse(userInputArr[1], out Y);
if (Y == 0)
{
//dividing by 0 is not allowed
Console.WriteLine("divisao impossivel");
continue; //go to next iteration
}
double divisao = X / Y; // Digite aqui o calculo da divisao
Console.WriteLine("Answer: " + divisao.ToString("F1") + "n");
}
else
{
Console.WriteLine("nError: Invalid input. Please try again.");
}
}
} while (true);
}

注意:如果使用","而不是"。"对于使用"0"的双值;en-US";键盘

由于您使用的是不同的语言,因此还需要提供CultureInfo

// using System.Globalization;
Console.WriteLine(divisao.ToString("F1", CultureInfo.CreateSpecificCulture("pt-PT")));

我相信葡萄牙语使用,而不是英语中使用的.。要强制葡萄牙语十进制表示为字符串,必须定义CultureInfo。

最新更新