0

The following code in my Greedy program (getting float from user simplified for forum purposes!):

change = GetFloat();
// convert to int
int cInt = round(change*100);

// define arraw with values of coins
int coinTypes[4] = {25, 10, 5, 1};
int coinTypeAmt = sizeof(coinTypes)/sizeof(int);

for (int i = 0; i < coinTypeAmt; i++)
{
    int remainder = cInt % coinTypes[i];
    printf("  remainder: %d\n", remainder);
}

Why will remainder be always wrong for the first value (25) if I input a value smaller than 0.25 cents in the prompt?

0.15 for example will give me a remainder of 15
0.03 - remainder will be 3
0.02 - remainder will be 2

Now that I write this, I realize the remainder is always the same as cInt if cInt is smaller than 25.

Any other values seem to work fine...

Why is that??

Thanks! Best, Daniel

1
  • By virtue of the modulo function, if a value is less than the value you mod it by, mod returns the initial value because the quotient is zero with remainder. If they are equal, mod yields zero because the divisor and dividend yield quotient 1 with no remainder. Add one more to the dividend, and now the quotient is 1 with a remainder; the remainder is the value modulo reports. As an example, 12 % 25 = 12, because 12 / 25 = 0 r 12. However, 27 % 25 = 2, because 27 / 25 = 1 r 2. And 25 % 25 = 0 because 25 / 25 = 1. Commented Mar 12, 2015 at 22:32

1 Answer 1

2

That's how the remainder operator just works. You may think of it that way:

given a = 3 and b = 2, the expression

a % b // results in 1

because a 3 can have a maximum of a single (i.e., one) 2 in it. Now what's the remainder? It's the difference between 3 and (2 x 1) and that's definitely 1.

Now let a = 2 and b = 3, the expression

2 % 3 // results in 2

because, in the same sense, 2 has zero 3s in it. What's the remainder? It's the difference between 2 and (3 x 0) and that's definitely 2.

You may play with other values as well, here are a couple more examples

let a = 9 and b = 2

9 % 2 // results in 1

because 9 has a maximum of four twos (i.e., 2 x 4) and the remainder is 9 - (2 x 4) = 1

let a = 2 and b = 9

2 % 9 // results in 2

because 2 has zero nines (i.e., 0 x 9) and the remainder is 2 - (0 x 9) = 2.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .