c# - 输入字符串的格式不正确 - 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
如果输入一个非整数字符然后尝试将其解析为整数,则会发生错误,双精度也是如此。改为使用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);
}
注意:如果使用“,”而不是“。”,上述方法也适用。对于使用“en-US”键盘的双精度值。
推荐阅读
- python - 如何在不使用 numpy 的情况下创建零矩阵?
- android - 'void com.algolia.instantsearch.core.helpers.Searcher.destroy()' 在空对象引用上
- linux - 将文件 os.rename() 重命名为时间戳会返回奇怪的字符串
- javascript - Javascript addEventListener 不允许多个鼠标事件
- spring-boot - 春季集成领导选举在向控制总线发送消息时使用jdbc锁注册表撤销领导
- ios - iOS - 带有内容插入的粘性标题 - 标题视图不像单元格那样滚动
- javascript - 使用条件运算符运行多个语句将不起作用
- java - 如何在不为 WEKA 中的实例创建 ARFF 文件的情况下对实例进行预测?
- php - Croppie base64 图像损坏
- ruby-on-rails - Rails 5 升级错误 - Bundler 找不到 gem "actionpack" 的兼容版本: