【发布时间】:2020-05-26 18:21:40
【问题描述】:
Console.WriteLine("Amount Spent (0.00):");
float amount;
string amountString;
bool repeat = false;
do
{
repeat = false;
amountString = Console.ReadLine();
try
{
amount = float.Parse(amountString);
}
catch (FormatException)
{
Console.WriteLine("Numeric Value Required.");
repeat = true;
}
catch (OverflowException)
{
Console.WriteLine("Number too large/small for float.");
repeat = true;
}
catch (Exception)
{
Console.WriteLine("Invalid Input.");
repeat = true;
}
}
while (repeat);
return float.Parse(amountString);
此代码适用于常规数字,但是如果我开始输入大得离谱的数字,我会得到返回值 8。我预计 OverFlowException 会捕获一个太大的数字。它不应该抓住他们吗?
如果我输入:
50000000000000000000000000000000000000
我得到诸如 5E+37 之类的值,这与精度有关,但我希望如此。但是如果再长一位,它只会返回 8。我认为这是因为它太大了,但我认为 tryCatch 中的 OverflowException 应该捕获它不应该吗?
【问题讨论】:
-
你问的是解析int还是float?你的标题说一个,代码说另一个。
-
如果您使用浮点数,欢迎来到浮点数学的不确定性:youtube.com/watch?v=PZRI1IfStY0
-
我把你的代码放在dotnetfiddle.net 和 500000000000000000000000000000000000000 抛出溢出异常。这是你的完整代码吗?另外,您为什么要再次解析它而不是返回“金额”?
-
目前您使用的是哪个 .NET 版本?根据它,您可能会得到异常(.NET Core 3.x 和 .NET Fw 之前的版本)或无穷大值(.NET Core 3.x)
标签: c# parsing floating-point