c# - DivideByZeroException 不起作用并给出随机整数(例如 8)
问题描述
{
**result4 = num1 / num2;**
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(name + " this is the final result of Divsion = " + result4);
Console.ReadKey();
Environment.Exit(0);
}
else if (op == "^")
{
result5 = Math.Pow(num1, num2);
Console.ForegroundColor = ConsoleColor.Green;
Console.Write(name + " this is the final result of exponential calculations = " + result5);
Console.ReadKey();
Environment.Exit(0);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(name + " this operant does not match the listed operant...this terminal will be cleared and closed after any key is pressed");
Console.ReadKey();
Environment.Exit(0);
}
}
**catch(DivideByZeroException)**
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(name + " you can not divide by zero; math error");
}
这是脚本的一部分……但这是错误的主要部分。如果需要,我将发布完整的脚本。单词result 4 和catch 上面的两个星号表示两段代码。
解决方案
据我所知,双 0 实际上可以是 0,000000001。这意味着这不是除以零,而是除以非常小的数字,结果导致接近无穷大,这就是你得到的。
在这个例子中,您可以简单地测试您的 num2 是否足够接近零,如果是,则抛出异常。
If(Math.Abs(num2) < 0,00001)
Throw DivideByZeroException
推荐阅读
- sql - 为间隙和孤岛问题的变化提供 ID
- amazon-web-services - 允许内部团队只发布到 SQS
- string - USB 转串口适配器 - 在有限的时间内接收正常
- python - 在 Visual Studio 中创建 python 虚拟环境失败:返回非零退出状态 1
- c++ - 日期验证。即使我的日期实际上是有效的,也会继续循环
- python - Python - 将 300 个变量插入 SQLite
- python - Python 通过 selenium 将图像上传到站点
- javascript - 传单R,如何使与儿童统计相关的聚集图标出现?
- css - 右下角带有图标和文字的圆形功能区
- c# - 如何知道由多个对象实现的协同程序何时结束?