divide by zero

This is a discussion on divide by zero within the C Programming forums, part of the General Programming Boards category; Code: #include<stdio.h> void main() { int i=60;int j=0; j=i/j; printf("%d\n",j); } this code was compiled with gcc 4.4.5 on Ubuntu, ...

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    1

    divide by zero

    Code:
    #include<stdio.h>
    
    void main()
    {
      int i=60;int j=0;
      j=i/j;
      printf("%d\n",j);
    }
    this code was compiled with gcc 4.4.5 on Ubuntu, on execution an error message was thrown as "Floating point exception" But on changing datatype of j to float it produced "inf". I m not able to understand why it is not working same with j as int.

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    2,517
    "inf" is defined as part of the IEEE float standard. IEEE 754-2008 - Wikipedia, the free encyclopedia
    in other words the "inf" is not part of an int computer number standard.

    Tim S

  3. #3
    Registered User
    Join Date
    Apr 2006
    Posts
    2,021
    Because for IEEE floating point numbers, dividing a regular number by 0 yeilds inf.

    For integers, dividing by 0 generally causes an interrupt. There is no standard result that is used.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  4. #4
    Registered User
    Join Date
    Jun 2005
    Posts
    6,208
    If your compiler supports IEEE floating point, dividing by zero gives a "special" infinite value.

    The C standard does not actually require that floating point values be represented using IEEE standard formats. There are real compilers that do not use IEEE formats (and I remember using one compiler that only used IEEE floating point if enabled using a command line switch).

    Dividing by zero gives undefined behaviour according to the C standard. Which means any result is acceptable (reporting inf, crashing, etc). There is also no requirement for consistent behaviour between types.
    Right 98% of the time, and don't care about the other 3%.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How do you Divide in C?
    By Nothing595 in forum C Programming
    Replies: 3
    Last Post: 10-02-2010, 05:32 PM
  2. divide by zero
    By George2 in forum C# Programming
    Replies: 17
    Last Post: 05-02-2008, 02:37 AM
  3. Divide by 3 in ISR
    By Roaring_Tiger in forum C Programming
    Replies: 40
    Last Post: 08-21-2004, 11:51 AM
  4. Cannot divide
    By /nFallen in forum C++ Programming
    Replies: 3
    Last Post: 05-02-2003, 04:35 PM
  5. divide
    By Luigi in forum C++ Programming
    Replies: 8
    Last Post: 02-04-2003, 06:38 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21