C# 解析c语言中的十进制数

C# 解析c语言中的十进制数,c#,C#,我试图在我的一个方法中解析一个十进制数,但它总是给我一个运行时错误,我不明白为什么。我必须计算一个物体的最终速度,但每次我尝试输入一个十进制数作为值时,它都会给我一个运行时错误,重点是我在哪里解析了十进制数 private static decimal GetVelocity() { Console.Write("Please enter the intial velocity of the object: "); decimal mVelocity =

我试图在我的一个方法中解析一个十进制数,但它总是给我一个运行时错误,我不明白为什么。我必须计算一个物体的最终速度,但每次我尝试输入一个十进制数作为值时,它都会给我一个运行时错误,重点是我在哪里解析了十进制数

private static decimal GetVelocity()
    {
        Console.Write("Please enter the intial velocity of the object: ");
        decimal mVelocity = decimal.Parse(Console.ReadLine());
        return mVelocity;
    }
有人能告诉我我做错了什么吗?

decimal.Parse需要一个有效的decimal,否则它将抛出一个错误。在默认区域性的大多数情况下,1.5、1和100.252都是有效的小数。您正在使用的区域性可能正试图使用不正确的分隔符转换十进制,如,。有关如何使用重载的decimal.TryParse提供区域性特定信息的信息,请参见

理想情况下,应使用decimal.TryParse尝试转换它,否则显示错误:

private static decimal GetVelocity()
{
    Console.WriteLine("Please enter the intial velocity of the object: ");
    decimal mVelocity;
    while ( !decimal.TryParse(Console.ReadLine(), out mVelocity) )
    {
        Console.WriteLine("Invalid velocity. Please try again: ");
    }
    return mVelocity;
}

如果输入的格式无效,解析将引发异常。你有两个选择

将解析调用包装在try/catch块中

decimal mVelocity;

try {
    mVelocity = decimal.Parse(Console.ReadLine());
}
catch(Exception e){}
或者改用胰蛋白酶


您的代码正在引发异常,因为无法将输入解析为十进制

您好,您可以改用正则表达式

private static decimal GetVelocity()
    {
        Console.Write("Please enter the intial velocity of the object: ");
        decimal mVelocity = decimal.Parse(Console.ReadLine());
        return mVelocity;
    }
    private static decimal GetVelocity()
    {
        Regex regex = new Regex(@"^[0-9]([.,][0-9]{1,3})?$");
        Console.Write("Please enter the intial velocity of the object: ");
        string decimalInput = Console.ReadLine();

        while (!regex.IsMatch(decimalInput))
        {
            Console.WriteLine("Wrong input");
            decimalInput = Console.ReadLine();
        } 

        decimal mVelocity = decimal.Parse(decimalInput);
        return mVelocity;
    }

错误是什么?错误是什么?您正在键入的数字是什么?您在控制台中键入的是什么?很可能,您正在使用逗号作为十进制分隔符或从不信任用户输入。使用decimal.TryParse而不是decimal.Parse。事实上,您的答案并不完全正确,这取决于区域设置,coma或full stop@Сзззззззззз更新了我的答案