Thread: I need some explanation why this happens

  1. #1
    Registered User
    Join Date
    Oct 2017
    Posts
    36

    I need some explanation why this happens

    Hi, I wonder why this program works the way it does. it took some time to figure what was going on but when i did i could not really explain why.

    Code:
    int fruits = 45;                  /* Amount of Fruits I have to sell */
    int buyers = 7;                 /* Number of buyers */
    int amount_per_buyer = 45 / 7;
    
    printf("Each buyer bought %d amount of fruits.\n\n", amount_per_buyer);
    
    return(0);
    The problems is within the division 45 / 7 returns 6 with a remainder of i guess 4 from my calculator. But it never prompts you that there was a remainder. I guess this could lead to a bug in a banking application.

    Please kindly put me right. Thanks

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    That's how integer division works. You can't store the fraction anywhere.
    Use double if you want fractions.
    But beware of rounding errors as well, floats are not good for money in general.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Oct 2017
    Posts
    36
    Hello Salem, Thanks for your reply. I read elsewhere that to avoid such i can make use of other data types like Float, Double or Long double.

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    One common approach to representing money is to work in cents (whole numbers, using ints) instead of dollars, to avoid the precision issues associated with real types.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need some explanation here...
    By 0celot in forum C Programming
    Replies: 6
    Last Post: 01-10-2012, 08:46 PM
  2. Explanation pls
    By dpp in forum C++ Programming
    Replies: 6
    Last Post: 09-05-2009, 02:08 PM
  3. @ explanation pls
    By WDT in forum C# Programming
    Replies: 4
    Last Post: 04-22-2009, 08:23 PM
  4. Explanation Please
    By atari400 in forum C++ Programming
    Replies: 2
    Last Post: 04-25-2003, 08:39 AM
  5. Further Explanation
    By sketchit in forum C Programming
    Replies: 1
    Last Post: 09-24-2001, 12:23 PM

Tags for this Thread