Divide by zero error, how do I fix this?

2020-08-13 08:07发布

C# novice here, when the int 'max' below is 0 I get a divide by zero error, I can see why this happens but how should I handle this when max is 0? position is also an int.

    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
        {
        }
    }

10条回答
啃猪蹄的小仙女
2楼-- · 2020-08-13 08:36

Well, that entirely depends on the behaviour you want. If the maximum value of your program bar is zero, is it full? Is it empty? This is a design choice, and when you've chosen, just test for max == 0 and deploy your answer.

查看更多
相关推荐>>
3楼-- · 2020-08-13 08:38

Convert your

int percent = (100 * position) / max;

into

int percent;
if (max != 0)
    percent = (100 * position) / max;
else
    percent = 100; // or whatever fits your needs
查看更多
等我变得足够好
4楼-- · 2020-08-13 08:43
  • You can throw an exception.
  • You can do int percent = ( max > 0 ) ? (100 * position) / max : 0;
  • You can choose to do nothing instead of assigning a value to percent.
  • many, many other things...

Depends on what you want.

查看更多
家丑人穷心不美
5楼-- · 2020-08-13 08:44

Well, if max is zero, then there is no progress to be made. Try catching the exception where this is called. That is probably the place to decide whether there is a problem or if the progress bar should be set at zero or at 100%.

查看更多
神经病院院长
6楼-- · 2020-08-13 08:46

You would need a guard clause which checks for 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);
}

You could also handle the Divide by Zero exception, as your sample showed, but it is generally more costly to handle exceptions then to set up checks for known bad values.

查看更多
三岁会撩人
7楼-- · 2020-08-13 08:47

Check for zero.

if ( max == 0 ) {
    txt = "0%";
} else {
    // Do the other stuff....
查看更多
登录 后发表回答