繁体   English   中英

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

[英]Divide by zero error, how do I fix this?

C# 新手,当下面的 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

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

  • 您可以抛出异常。
  • 你可以做int percent = ( max > 0 ) ? (100 * position) / max : 0; int percent = ( max > 0 ) ? (100 * position) / max : 0;
  • 您可以选择什么都不做,而不是为百分比分配一个值。
  • 很多很多其他的东西......

取决于你想要什么。

检查零。

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

这不是 C# 问题,而是数学问题。 除以零是未定义的。 有一个 if 语句来检查 max > 0 是否然后只执行你的除法。

转换您的

int percent = (100 * position) / max;

进入

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

好吧,如果 max 为零,那么就没有进展。 尝试捕获调用 this 的异常。 这可能是决定是否存在问题或进度条是否应设置为零或 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 = max != 0 ? (100 * position) / max : 0;

这意味着当 max 不等于零时,执行计算。 如果它等于 0,那么它将百分比设置为 0。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM