I am working on a program to work out the least number of coins for an amount of change given by the user.
It is meant to check for values of 0.25, 0.10, 0.05 and 0.01. If the user's value is greater than, or equal to one of these (in a set of successive if statements) an extra coin is added to the coin count and that amount is taken away from the user's original number.
Then, when the user's number is less than 0.01, the program is supposed to end and print the coin count.
I have read this code through several times and tried to fix it but I can't see a problem, can you help me with it?
0.25 shows 1 coin (correctly) but 0.26 shows 1 coin (incorrectly), for some reason missing my later if statement.
The 2 blocks of code controlling 0.25 and 0.01 are copied and pasted except or the coin value, so what's going on?
Thanks, Raisu
#include <stdio.h>
#include <cs50.h>
int main (void)
{
/**
* Declare all variables
*/
float UserInput = 0.00;
float Coin1 = 0.25;
float Coin2 = 0.10;
float Coin3 = 0.05;
float Coin4 = 0.01;
int CoinCount = 0;
/**
* Ask user for change amount and check it is more than 0, then print it
*/
do
{
printf("Please put the amount of change, in the format 0.00\r\n\r\n");
UserInput = GetFloat();// Get a float, check format
}
while (UserInput <0 || UserInput == 0);
printf ("You have entered %f\r\n\r\n",UserInput);
/**
* If userinput is over or equal to 0.25, take off 0.25 and add 1 to the coin count
*/
if (UserInput>=0.25)
{
do
{
UserInput -= Coin1;
CoinCount +=1;
}
while (UserInput >= Coin1);
printf ("\r\n%i of %f Pieces\r\n",CoinCount,Coin1);
}
/**
* If userinput is over or equal to 0.10, take off 0.10 and add 1 to the coin count
*/
if (UserInput >=0.10)
{
do
{
UserInput -= Coin2;
CoinCount +=1;
}
while (UserInput >= Coin2);
printf ("\r\n%i of %f Pieces\r\n",CoinCount,Coin2);
}
/**
* If userinput is over or equal to 0.05, take off 0.05 and add 1 to the coin count
*/
if (UserInput >=0.05)
{
do
{
UserInput -= Coin3;
CoinCount +=1;
}
while (UserInput >= Coin3);
printf ("\r\n%i of %f Pieces\r\n",CoinCount,Coin3);
}
/**
* If userinput is over or equal to 0.01, take off 0.01 and add 1 to the coin count
*/
if (UserInput >=0.01)
{
do
{
UserInput -= Coin4;
CoinCount +=1;
}
while (UserInput >= Coin4);
printf ("\r\n%i of %f Pieces\r\n",CoinCount,Coin4);
}
printf("\r\nTotal Coins Needed: %i\r\n*********************\r\n\r\n\r\n",CoinCount);
}