尝试除以零 [英] Attempt to divide by zero
问题描述
我一直把这个错误尝试除以零。
代码
i keep getting this error attempt to divide by zero.
code
private void tbLayers_TextChanged(object sender, EventArgs e)
{
int SqIn, comBo;
int.TryParse(tbSqIn.Text, out SqIn);
int.TryParse(cbPalett.Text, out comBo);
tbTotesPerLayers.Text = (comBo / SqIn).ToString();
我是什么尝试过:
What I have tried:
combo / ((SqIn == 0) ? 0 : SqIn)
推荐答案
两者
Both
... (comBo / SqIn);
和
and
...combo / ((SqIn == 0) ? 0 : SqIn);
产生完全相同的结果,第二种形式os更复杂。
正确的问题是你希望 SqIn
为零?
如果你希望 SqIn
为零,你必须在尝试除以之前检查它。
In
produce exactly the same result, second form os just more complicated.
The right question is "Do you expect SqIn
to be zero ? or not ?"
If you expect SqIn
to be zero, you must check it before trying to divide.
In
int.TryParse(tbSqIn.Text, out SqIn);
您不检查 TryParse
v是否已完成。
如评论中所述s,你需要先检查零。在我试过的部分你编写了代码,如果SqIn为0然后除以0.该语句是多余的,什么也不做。
你可以做的一招使用是这样的:
As mentioned in the comments, you need to check for zero first. In the what I have tried section you wrote code that if SqIn is 0 then divide by 0. The statement is redundant and does nothing.
A trick you might be able to use is something like:
combo / (SqIn + 0.0000000001)
这样做是为了使得除以零的可能性不会发生如果你不需要很高的数学精度,这是一个解决方法。
或者,只需检查0.简单。
What this does is makes it so that divide by zero most likely won't ever happen and if you don't need great accuracy in the math, this is a workaround.
Or, just check for 0. Simple.
如果SqIn为0,只需返回组合或任何你想要的。
If SqIn is 0, just return combo or whatever you want.
tbTotesPerLayers.Text = SqIn == 0 : combo.ToString() ? (comBo / SqIn).ToString();
这篇关于尝试除以零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!