首页 > 解决方案 > 输入字符串的格式不正确 - 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"));
            }
        }
    }
}

有任何想法吗?

标签: c#

解决方案


您没有说明错误发生的位置。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”键盘的双精度值。


推荐阅读