被零除 [英] Division by zero

查看:63
本文介绍了被零除的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个功能:

I had a function:

double Normalize(double v, double c)
{
    return 1.0 / (1.0 - (v * v) / (c * c)); 
}



它可以正常工作,直到我错误地用零参数调用它:



It worked correctly until I called it with zero argument by mistake:

double x = Normalize(2, 0);
Console.WriteLine(x);


输出0,无异常.怎么会?!每个人都不可能被零除.


It outputs 0, no exception. How come?! Everyone learned divide by zero is impossible. How can I be sure calculation is correct if there is division by zero in the middle?

推荐答案

当您将函数(2,0)作为参数传递时,您将如何递归?它将int值转换为整数,并要求它隐式地将它们强制转换为double类型.结果是不确定的,并且结果的LSB中可能有悬挂的非零位.对该值进行平方并除以它可以产生任何结果,包括0和无穷大.如果您传递函数(2.0,0.0),它们是显式的浮点值,我想您会得到预期的异常.
When you passed the function (2,0) as arguments, you handed it int values and asked it to implicitly cast them to type double. The results are indeterminate, and there may be dangling non-zero bits in the LSB of the result. Squaring that value and dividing by it can produce any result, including 0 and infinity. If you pass the function (2.0, 0.0), which are explicit floating point values, I think you''ll get the exception you''re expecting.


如果需要,则需要分配一个子句以简化这样的假设:如果用户分配零,则显示按摩,例如:

在public中初始化变量并编写:

We need to assign one if clause to spacify the condiction that if a user assign zero show the maassage like:

initialize the variable in public and write:

double x;
double y;
double z;
string op;



在透明按钮下,我们写:



under oparent button we write:

x=system.convert.tostring(texbox?.text);
op=/;
if(y=0)
{
massagebox.show("can''t be devided");
}



萨菲拉
阿富汗



Safiullah
Afghanistan


Yo可以将操作分开,然后检查划分是否为无限

Yo could separate the operations and then check if the division is Infinite

if(double.IsInfinity(down))
{
  //Exception
}



或验证这种情况,如果您的"c"为0,则为例外



or validate this case, if your "c" is 0, then exception


这篇关于被零除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆