Ronald Prithiv - 6 months ago 66

C Question

I am writing a program that takes an input and should print out the least number of coins used. When I run the program and type in an input, it doesn't work as expected and doesn't print anything. What am I doing wrong here?

`#include <stdio.h>`

#include <cs50.h>

int main (void)

{

float f = 0;

int count = 0;//number of coins

do

{

printf("How much change is owed?\n");

f = GetFloat();

}

while (f < 0);

//Convert to cents

f = f * 100;

while (f > 0)

{

if (f > 25)

{

f = f - 25;

count++;

}

else if (f > 10)

{

f = f - 10;

count++;

}

else if (f > 5)

{

f = f - 5;

count++;

}

else if (f > 1)

{

f = f - 1;

count++;

}

}

printf("%d", count);

}

It doesn't print anything

Answer

The problem is that the program is stuck in an infinite loop. Initially, `f=0.41`

. Then, you do `f = f * 100`

; and we have `f = 41`

.

Then, as you move through the loop,

First, `f>25`

, so `f = f - 25`

, and you get `f = 16`

.

Then, next iteration, `f>10`

, so `f = f - 10`

, and you get `f = 6`

.

Then, `f>5`

, so `f = f - 5`

, and you get `f = 1`

.

Now, none of the if conditions in the loop are satisfied, but the condition in the while remains true. So, it never breaks out. To correct this, replace all `>`

symbols in the if blocks with `>=`

. This will give you the correct number of coins. (but you must ensure that `f`

does not have any fractional part after `f = f * 100`

).

```
f = (int)(f * 100);
while (f > 0)
{
if (f >= 25)
{
f = f - 25;
count++;
}
else if (f >= 10)
{
f = f - 10;
count++;
}
else if (f >= 5)
{
f = f - 5;
count++;
}
else if (f >= 1)
{
f = f - 1;
count++;
}
}
```