SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Apr 2013
    Posts
    3
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Why do I get a divide-by-zero error?

    I found this forum thanks to an old post on how to check whether a number is an integer:

    Quote Originally Posted by KevinR
    in your example this would be simple:
    Code:
        if (/\D/) {
           is not an integer
        }
    the regular expression checks if there are any non-digit characters in the string. Since there is a dot it returns true and the string is not an integer.
    I wrote a one-line program to try this out, with unexpected results:

    Code:
    perl -e 'print "Result of division is not an integer.\n" if 14/7 =~/\D/'
    Illegal division by zero at -e line 1.
    Why the error? Clearly, I'm dividing by seven. Here's a very similar one-liner that works as expected:

    Code:
    perl -e 'print "Fourteen divided by seven is two.\n" if 14/7 == 2'
    Fourteen divided by seven is two.
    Why does the first give a divide-by-zero error, while the second does not?

    Thanks

  2. #2
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,149
    Mentioned
    14 Post(s)
    Tagged
    0 Thread(s)
    Probably an operator precedence issue. I suspect your code is being interpreted like this:

    if 14/(7 =~/\D/)
    "First make it work. Then make it better."

  3. #3
    SitePoint Member
    Join Date
    Aug 2011
    Posts
    19
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Jeff Mott View Post
    Probably an operator precedence issue. I suspect your code is being interpreted like this:

    if 14/(7 =~/\D/)
    Your suspicion is correct.

    Code:
    perl -e 'print "Result of division is not an integer.\n" if (14/7) =~/\D/'
    works fine.

    That said, the more standard way of testing whether a value is an integer is:
    Code:
    perl -e 'print "Result of division is not an integer.\n" if 14/7 != int 14/7'
    The intention is clearer this way, since you're explicitly testing whether the value is equal to the integer portion of the value instead of looking for the presence of non-numeric characters, which you could be doing for many other reasons.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •