除以零错误,我该如何解决这个问题?

10 c# divide-by-zero

C#新手在这里,当下面的int'max'为0时我得到除零错误,我可以看出为什么会发生这种情况但是当max为0时我应该如何处理呢?位置也是一个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
        {
        }
    }
Run Code Online (Sandbox Code Playgroud)

Sim*_*mon 16

int percent = 0
if (max != 0) percent = (100*position) / max
Run Code Online (Sandbox Code Playgroud)


Ada*_*ght 9

那么,这完全取决于你想要的行为.如果程序栏的最大值为零,它是否已满?它是空的吗?这是一个设计选择,当您选择时,只需测试max == 0并部署您的答案.


Swa*_*ati 8

  • 你可以抛出异常.
  • 你可以做 int percent = ( max > 0 ) ? (100 * position) / max : 0;
  • 您可以选择不执行任何操作,而不是将值分配给百分比.
  • 很多很多其他的东西......

取决于你想要什么.