How different programming languages handle divisio

2020-03-24 04:40发布

Perhaps this is the wrong sort of question to ask here but I am curious. I know that many languages will simply explode and fail when asked to divide by 0, but are there any programming languages that can intelligently handle this impossible sum - and if so, what do they do? Do they keep processing, treating 350/0 as 350, or stop execution, or what?

10条回答
爷、活的狠高调
2楼-- · 2020-03-24 04:49

Floating point numbers as per the IEEE define constants NaN etc. Any continued operation involving thst value will remain unchanged until the end. Integer or whole numbers are different with exceptions being thrown...In java...

查看更多
我命由我不由天
3楼-- · 2020-03-24 04:50

In Delphi, it either throw a compile-time error (if divided by a 0 value const) or a catchable runtime error if it happens at runtime.

It's the same for C and C++.

In PHP you will get a warning:

Warning: Division by zero in <file.php> on line X

So, in PHP, for something like:

$i = 123 / 0;

$i will be set to nothing. BUT $i is not === NULL and isset($i) returns true and is_string($i) returns false.

查看更多
smile是对你的礼貌
4楼-- · 2020-03-24 04:51

Python (at least version 2, I don't have 3) throws a ZeroDivisionError, which can be caught.

num = 42
try:
    for divisor in (1,0):
        ans = num / divisor
        print ans
except ZeroDivisionError:
    print "Trying to divide by 0!"

prints out:

42
Trying to divide by 0!
查看更多
神经病院院长
5楼-- · 2020-03-24 04:56

From Wikipedia:

The infinities of the extended real number line can be represented in IEEE floating point datatypes, just like ordinary floating point values like 1, 1.5 etc. They are not error values in any way, though they are often (but not always, as it depends on the rounding) used as replacement values when there is an overflow. Upon a divide by zero exception, a positive or negative infinity is returned as an exact result.

查看更多
干净又极端
6楼-- · 2020-03-24 04:56

I'm working with polyhedra and trying to choose a language that likes inf. The total edges for a polyhedron {a,b} where a is edges per polygon and b is edges per corner is E = 1/(1/a + 1/b - 1/2)

if E is negative it's a negative curvature, but if E is infinity (1/0) it tiles the plane. Examples: {3,6} {4,4}

查看更多
走好不送
7楼-- · 2020-03-24 04:59

In Java, division by zero in a floating-point context produces the special value Double.POSITIVE_INFINITY or Double.NEGATIVE_INFINITY.

查看更多
登录 后发表回答