为什么除以零是一个无法恢复的问题?

发布于 2024-09-25 11:15:02 字数 397 浏览 6 评论 0原文

为什么 java 不能优雅地返回除以零的值,而必须抛出异常?

我收到一个 ArrayIndexOutOfBoundsException:0 这是因为 DamageTaken 实际上是一个存储许多不同“损坏”的值数组。

在java中我试图创建一个进度条。我们的示例:在赛车游戏中,通过将高度值设置为游戏结束前允许的最大伤害的百分比来产生伤害。

在程序开始时,damageTaken = 0;

(damageTaken / maximumDamage)

将给出 0 - 1 之间的数字。

然后我只需将其乘以进度条的高度,即可创建适当高度的填充条。

程序崩溃了。我希望进度条的高度为零!

Why can't java gracefully return some value with a division by zero and instead has to throw an Exception?

I am getting an ArrayIndexOutOfBoundsException:0 This is because because damageTaken is actually an array of values that stores many different 'damages'.

In java I'm trying to create a progress bar. Our example: damage incurred, in a racing game, by setting the value for height as a percentage of maxmimum damage allowed before gameover.

At the start of the program damageTaken = 0;

(damageTaken / maximumDamage)

will give numbers between 0 - 1.

Then I just multiply that by the height of the progress bar, to create a fill bar of the appropriate height.

The program crashes. I want the progress bar to be of zero height!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

゛清羽墨安 2024-10-02 11:15:02

您不是除以零,而是将零除以某物

完全允许取两半零。答案是零。假设你有零个苹果。你把零个苹果分给了爱丽丝和鲍勃。爱丽丝和鲍勃现在都有零个苹果。

但是,你不能除以零。假设你有两个苹果。现在,您想将这些苹果送给零个人。每人得到多少个苹果?答案是未定义的,因此除以零是不可能的。

You are not dividing by zero, you are dividing zero by something.

It is completely allowed to take two halves of zero. The answer is zero. Say you have zero apples. You split your zero apples between Alice and Bob. Alice and Bob now both have zero apples.

But, you cannot divide by zero. Say you have two apples. Now, you want to give these apples to zero people. How many apples does each person get? The answer is undefined, and so division by zero is impossible.

九公里浅绿 2024-10-02 11:15:02
(damageTaken / maximumDamage)

仅当 maximumDamage 为零时,才会出现被零除异常。

如果 damageTaken 为零,则没有问题。

(damageTaken / maximumDamage)

This gives you a division by zero exception only if maximumDamage is zero.

If damageTaken is zero, there is no problem.

孤蝉 2024-10-02 11:15:02

只需添加 0 的特殊情况即可;

private int getProgress()
    if (damageTaken == 0) {
        return 0;
    } else {
        return (damageTaken / maximumDamage) * progress.getHeight();
    }
}

但是,(但是它很大)除以 0 的原因是因为 maximumDamage 是 0,不是 damageTaken< /代码>。所以,您可能真正想要的是:

private int getProgress()
    if (maximumDamage== 0) {
        return 0;
    } else {
        return (damageTaken / maximumDamage) * progress.getHeight();
    }
}

Just add a special case for 0;

private int getProgress()
    if (damageTaken == 0) {
        return 0;
    } else {
        return (damageTaken / maximumDamage) * progress.getHeight();
    }
}

However, (and it's a big however) the reason you are getting divide by 0 is because maximumDamage is 0, not damageTaken. So, what you probably really want is:

private int getProgress()
    if (maximumDamage== 0) {
        return 0;
    } else {
        return (damageTaken / maximumDamage) * progress.getHeight();
    }
}
人海汹涌 2024-10-02 11:15:02

从概念上讲,使用 4/0 产生任意数字并不比尝试将 2000000000 的计数加倍产生 -294967296 的计数更糟糕。然而,大多数处理器将忽略大多数类型的算术溢出,除非明确检查它,但不能忽略除以零的尝试,除非事先明确检查操作数(如果操作数无效则跳过该操作)。鉴于许多处理器都有“溢出”标志,没有什么可以阻止处理器指定尝试除以零除了设置溢出标志之外什么也不做(成功的除法操作应该清除它);在这种情况下想要触发异常的代码可以这样做。

我怀疑这种独特行为的原因源于计算的早期阶段。当余数小于除数时,除法指令的硬件可以判断除法完成。如果这种情况从未发生,指令可能会停止,直到通用监控时钟电路(设计用于在指令由于某种原因停止执行时发出故障信号)关闭为止。按照今天的标准,检测问题并在不停止 CPU 的情况下退出的硬件是微不足道的,但在计算机由分立晶体管构建的时代,告诉程序员不要尝试除法会更便宜,而且几乎同样有效永远为零。。

Conceptually, having 4/0 yield some arbitrary number would be no worse than having an attempt to double a count of 2000000000 yield a count of -294967296. Most processors, however, will ignore most kinds of arithmetic overflow unless one explicitly checks for it, but cannot ignore an attempt to divide by zero unless one explicitly checks the operands beforehand (and skips the operation if they are invalid). Given that many processors have "overflow" flags, nothing would prevent a processor from specifying that an attempted divide-by-zero should simply do nothing but set the overflow flag (a successful divide operation should clear it); code which wants to trigger an exception in such a case could do so.

I suspect the reason for the distinct behavior stems from the early days of computing; the hardware for a division instruction could judge that it was complete when the remainder was less than the divisor. If that never happened, the instruction could get stalled until a general supervisory clock circuit (designed to signal a fault if for whatever reason instructions stop being executed) shut things down. Hardware to detect the problem and exit without stalling the CPU would have been trivial by today's standards, but in the days when computers were built from discrete transistors it was cheaper, and almost as effective, to tell programmers do not attempt to divide by zero, ever.

鲸落 2024-10-02 11:15:02

让我们停止谈论非法行为,就好像穿着制服的数学警察即将冲进房间一样。 ;) 对于这背后的数学推理,此相关问题很有用。

公平地说,为什么现代编程平台不以某种标准方式为我们处理被零除的错误 - 但要回答这个问题:Java 与大多数其他平台一样其他平台,当除以零时会抛出错误。一般来说,您可以:

  • 处理之前:在进行除法之前检查要用作分母的变量是否为零
  • 处理之后:您可以捕获除以零时抛出的异常并进行处理优雅地。

请注意,作为良好实践,第二种方法仅适用于您不希望变量在正常系统操作下为零的情况。

所以是的,你需要一个特殊的案例来处理这种情况。欢迎来到编程。 ;)

Let's stop talking about illegality, as though uniformed mathematics police were about to storm the room. ;) For the mathematical reasoning behind this, this related question is useful.

It is fair to ask why, after all this time, modern programming platforms don't handle division-by-zero errors for us in some standard way - but to answer the question: Java, like most any other platform, throws an error when division by zero occurs. In general, you can either:

  • Handle before: check the variable to be used as your denominator for zero before doing the division
  • Handle after: you can catch the exception thrown when the division by zero occurs and handle it gracefully.

Note that, as good practice, the second method is only appropriate when you wouldn't expect the variable to ever be zero under normal system operation.

So yes, you need a special case to handle this situation. Welcome to programming. ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文