除以零错误,我该如何解决?

时间:2020-03-06 15:00:08  来源:igfitidea点击:

这里的Cnovice,当下面的int'max'为0时,我得到一个除以零的错误,我可以理解为什么会发生这种情况,但是当max为0时该如何处理呢?位置也是一个整数。

private void SetProgressBar(string text, int position, int max)
    {
        try
        {
            int percent = (100 * position) / max; //when max is 0 bug hits
            string txt = text + String.Format(". {0}%", percent);
            SetStatus(txt);
        }
        catch
        {
        }
    }

解决方案

int percent = 0
if (max != 0) percent = (100*position) / max

检查零。

if ( max == 0 ) {
    txt = "0%";
} else {
    // Do the other stuff....

好吧,这完全取决于我们想要的行为。如果程序栏的最大值为零,是否已满?它是空的吗?这是一种设计选择,选择后,只需测试max == 0并部署答案即可。

  • 我们可以抛出异常。
  • 你可以做'int percent =(max> 0)吗? (100 *位置)/最大值:0;`
  • 我们可以选择不执行任何操作,而不是将值分配给百分比。
  • 很多很多其他的事情...

取决于我们想要什么。

这不是一个Cproblem,而是一个数学问题。除零是不确定的。有一个if语句,检查max是否大于0,然后仅执行除法。

好吧,如果max为零,则没有任何进展。尝试在调用此方法的地方捕获异常。那可能是决定是否存在问题或者将进度条设置为零还是100%的地方。

我想根本的问题是:甚至在max为'0'的情况下调用此函数是否有意义?如果是,那么我要对其进行特殊处理,即:

if (max == 0) 
{
    //do special handling here
}
else
{
    //do normal code here
}

如果0没有意义,我将调查它的来源。

我们将需要一个保护子句来检查max == 0。

private void SetProgressBar(string text, int position, int max)
{
    if(max == 0)
        return;
    int percent = (100 * position) / max; //when max is 0 bug hits
    string txt = text + String.Format(". {0}%", percent);
    SetStatus(txt);
}

如样本所示,我们也可以处理被零除的异常,但是处理异常通常要比为已知的错误值设置检查要昂贵得多。

如果我们正在使用它进行下载,则可能会希望显示0%,因为在这种情况下,当我们还不知道文件大小时,我认为max == 0。

int percent = 0;
if (max != 0)
    ...;

如果我们将其用于其他长期任务,我想假设100%

而且,由于位置永远不能在0到-1之间,因此我们可能希望降低100 *

转换

int percent = (100 * position) / max;

进入

int percent;
if (max != 0)
    percent = (100 * position) / max;
else
    percent = 100; // or whatever fits your needs