Rory Rory - 3 months ago 18
C Question

C program counting coins with while loops

I've seen this particular C program mentioned quite a bit, albeit in some different forms. However I cannot seem to identify the source of my problem, or find another answer that helps. The program compiles and even executes correctly except for a single input: 4.2

The program appears to count the minimum number of coins needed to make the change entered as input, except for 4.2. It outputs 22 instead of 18 as it should (16 quarters, 2 dimes).
Any thoughts? I'm auditing an online course, no credit/no academic dishonesty issues.

#include <stdio.h>
#include <cs50.h>

int main(void)
{

//quarters, dimes, nickels, and total number of coins. a is float input for exact change.

float a;
int q=0;
int d=0;
int n=0;
int p=0;
int i;

//petitioning input
do
{
printf("Hello, how much change do I owe you?\n");
a = GetFloat();
}
while(a<=0);

//converting float a to an integer i
i= a*100;

//four 'while' loops checking quarters nickels dimes pennies and adding to coin count while
while(i>=25)
{
i=i-25;
q++;
}
while(i>=10 && i<25)
{
i=i-10;
d++;
}
while(i>=5 && i<10)
{
i=i-5;
n++;
}

while(i>0 && i<5)
{
i= i-1;
p++;
}

//printing sum of each coin type
{
printf("%d\n", q+d+n+p);
}
return 0;
}

Answer

You just counterfeited by floating point precision.

You declared

float a;

So, when

a = 4.2; // say

it looks something like

a = 4.19999981

So, i= a*100; is assigned 419 into i instead of 420 (what you are expecting).

Solution You need to convert float a into integer :

(int)(x + 0.5)

So, instead of i= a*100 try

i= a*100 + .5;
Comments