Pranav - 2 months ago 15

C Question

John has 5.10 in quarters, dimes and nickels. If he has 31 coins what are possibilities?

This is my code:

`#include <stdio.h>`

int main() {

int quarters, dimes, nickels;

for (quarters = 1; quarters <= 31; quarters++) {

for (dimes = 1; dimes <= 31; dimes++) {

for (nickels = 1; nickels <= 31; nickels++) {

if (quarters + dimes + nickels == 31 && quarters * .25 + dimes * .10 + nickels * .05 == 5.10) {

printf("%i quarters, %i dimes, %i nickels \n", quarters, dimes, nickels);

}

}

}

}

}

Gives the result:

`14 quarters, 15 dimes, 2 nickels`

15 quarters, 11 dimes, 5 nickels

17 quarters, 3 dimes, 11 nickels

My question is why does this code give 4 solutions?

`#include <stdio.h>`

int main() {

int quarters, dimes, nickels;

for (quarters = 1; quarters <= 31; quarters++) {

for (dimes = 1; dimes <= 31; dimes++) {

for (nickels = 1; nickels <= 31; nickels++) {

if (quarters + dimes + nickels == 31 && quarters * 25 + dimes * 10 + nickels * 5 == 510) {

printf("%i quarters, %i dimes, %i nickels \n", quarters, dimes, nickels);

}

}

}

}

}

Result:

`14 quarters, 15 dimes, 2 nickels`

15 quarters, 11 dimes, 5 nickels

16 quarters, 7 dimes, 8 nickels

17 quarters, 3 dimes, 11 nickels

Answer

5/100 and 10/100 are periodic numbers in binary just like 1/3 is a periodic number in decimal. This means it's impossible to represent them exactly as floating point numbers.