Thread: Modulus

  1. #1
    Registered User
    Join Date
    Apr 2017
    Posts
    2

    Modulus

    Hi, I'm having trouble understanding how modulus works. For an exercise I have to write a program where the user inputs how much change is needed in 2 dollar and 1 dollar coins as well as cents (50, 10, 5, 2, 1 cents). This is what I was thinking but doesn't work:

    int x = input % 200;
    int dollar2 = x / 200;
    int dollar1 = input % 100;
    int cent50 = x % 50;
    int cent20 = input % 20;
    int cent10 = x % 10;
    int cent5 = input % 5;
    int cent2 = x % 2;
    int cent1 = input % 1;

    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
    Define "it doesn't work".
    Tell us the difference between your expectation and reality (for example).

    It helps if you post an actual program we can run, not just a few random statements.
    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
    Jun 2015
    Posts
    1,640
    The first two statements are in the wrong order. You've already modified x before the division that assigns to dollar2. E.g., suppose x = 555. x % 200 yields 155, so now x is 155. Then you divide by 200, which yields 0 for dollar2, but it should have been 2. Clearly these need to be done in the opposite order.

    After that, you start using the modulus statements to incorrectly assign values to dollar1, cent50, etc. Those need to be division statements and you need modulus statements after each of them to modify x each time.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Modulus
    By Caiz in forum C Programming
    Replies: 3
    Last Post: 04-24-2017, 03:44 AM
  2. %(Modulus)
    By cuo741 in forum C Programming
    Replies: 19
    Last Post: 05-14-2010, 08:50 AM
  3. modulus
    By nicknack in forum C Programming
    Replies: 7
    Last Post: 12-15-2007, 09:45 AM
  4. Modulus question!
    By bobthebullet990 in forum C Programming
    Replies: 12
    Last Post: 01-05-2007, 08:54 AM
  5. Help with Modulus
    By boontune in forum C++ Programming
    Replies: 4
    Last Post: 01-20-2003, 10:26 AM

Tags for this Thread