首页 > 解决方案 > 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 上面的两个星号表示两段代码。

标签: c#

解决方案


据我所知,双 0 实际上可以是 0,000000001。这意味着这不是除以零,而是除以非常小的数字,结果导致接近无穷大,这就是你得到的。

在这个例子中,您可以简单地测试您的 num2 是否足够接近零,如果是,则抛出异常。

If(Math.Abs(num2) < 0,00001)
    Throw DivideByZeroException

推荐阅读