I have a do-while loop:
float amount;
do
{
printf("Input dollar amount owed:\n");
amount = GetFloat();
}
while (amount <= 0);
followed by a while loop and printf:
int coins = 0;
while (amount >= 0.25);
{
amount = amount - 0.25;
coins++;
}
printf("Number of coins to use: %d\n", coins);
return 0;
but when I run and use it, the while loop doesn't run and printf doesn't print. It looks like this in my terminal, where 1 is the user input:
Input dollar amount owed: 1
How do I get the program to move onto the while loop and printf?
while (amount >= 0.25);
^ roh roh
I think what you meant was:
while (amount >= 0.25)
{
amount = amount - 0.25;
coins++;
}
while(x); is the same as while(x) { }
This just looks like a syntax error in while (amount >= 0.25); it should be while (amount >= 0.25). just have to remove the semicolon.
It seems that you want to get the number of coins for each amount entered until a negative number is entered. To do this you want to nest the while loops. The pseudo code would be:
Get amount
Check if it is greater than 0
Get number of coins and print
Repeat
And the actual code could be something like:
float amount;
printf("Input dollar amount owed:\n");
amount = GetFloat();
while( amount >= 0 )
{
int coins = 0;
while (amount >= 0.25)
{
amount -= 0.25;
coins++;
}
printf("Number of coins to use: %d\n", coins);
printf("Input dollar amount owed:\n");
amount = GetFloat();
}
return 0;
However, your "Get number of coins" is simply doing a division followed by a floor operation. So that doesn't need a loop:
int coins = (int) (amount / 0.25f); // casting to an int will truncate the float.
Related
I just started programming, so I know this is probably a very basic error, but i've been trying to find out how to fix the logical error in my code for the greedy.c assignment from Harvard's CS50 course without success. I have looked up solutions to the problem, but they all seem to solve it in a different manner than I am trying. I have reverse engineered the other examples, and I understand them now, but I really want to know how to make my own version run well.
I am trying to get the problem done by a series of while loops, each of which subtract a certain coin value from the total owed, and adding one coin to the total coin count. To me, it seems like logically it makes sense, but when I run the program it doesn't give me the expected output. It just doesn't execute the printf statement at the bottom. I'm hoping one of you wizzes out there can give me a hand with this! Thanks for any help!
Heres my code:
#include <stdio.h>
#include <cs50.h>
int main (void)
{
printf("How much change is needed?\n");
float owed = get_float();
int coins = 0;
/*While loops subtracting one coin from change owed, and adding one to coin count*/
while (owed >= 0.25)
{
owed = owed - 0.25;
coins = coins + 1;
}
while (owed >= 0.1)
{
owed = owed - 0.1;
coins = coins + 1;
}
while (owed >= 0.05)
{
owed = owed - 0.05;
coins = coins + 1;
}
while (owed >= 0.01)
{
owed = owed - 0.01;
coins = coins + 1;
}
/*While loops done, now print value of "coins" to screen*/
if (owed == 0)
{
printf("You need %i coins\n", coins);
}
}
Edit:
So I played around with it a little more, and finished that "if" statement. It is returning error for me, so how is the value of "owed" by the end of the program not equal to 0?
#include <stdio.h>
#include <cs50.h>
int main (void)
{
printf("How much change is needed?\n");
float owed = get_float(); //Gets amount owed from user in "x.xx" format
int coins = 0; //Sets initial value of the coins paid to 0
//While loops subtracting one coin from change owed, and adding one to coin count
while (owed > 0.25)
{
owed = owed - 0.25;
coins = coins + 1;
}
while (owed > 0.1)
{
owed = owed - 0.1;
coins = coins + 1;
}
while (owed > 0.05)
{
owed = owed - 0.05;
coins = coins + 1;
}
while (owed > 0.01)
{
owed = owed - 0.01;
coins = coins + 1;
}
//While loops done, now print value of "coins" to screen
if (owed == 0)
{
printf("You need %i coins\n", coins);
}
else
{
printf("Error\n");
}
}
Edit:
So once my code was working, I started fiddling with it and overengineering. Heres the final(for now) version!
#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <time.h>
int main (void)
{
srand(time(0)); //generates random seed
float price = round(rand()%500); //generates random price between 0 and 500 cents
printf("You owe %f. How much are you paying?\n", price/100); //shows user their price between 0 and 5 dollars
printf("Dollars: ");
float paymnt = get_float()*100; //gets the amount user will pay in dollars then converts to cents
int owed = round (paymnt - price); //calculates the change owed by paymnt-price
int coins = 0; //Sets initial value of the coins paid to 0
int quarters= 0;
int dimes = 0;
int nickels = 0;
int pennies = 0;
if (owed ==0 && price >0) //If someone pays in exact
{
printf("You paid the exact amount!\n");
}
else if (owed < 0) //If someone doesn't pay enough
{
printf("You didn't give us enough money!\n");
}
else //Else(We owe them change)
{
printf("Your change is %i cents\n", owed);
//While loops subtracting one coin from change owed, and adding one to coin count
while (owed >= 25)
{
owed = owed - 25;
quarters = quarters + 1;
}
while (owed >= 10)
{
owed = owed - 10;
dimes = dimes + 1;
}
while (owed >= 5)
{
owed = owed - 5;
nickels = nickels + 1;
}
while (owed >= 1)
{
owed = owed - 1;
pennies = pennies + 1;
}
//While loops done, now print each coin and total coins needed to screen
if (owed == 0)
{
coins = quarters + dimes + nickels + pennies;
printf("You need %i coins (%i quarters, %i dimes, %i nickels, and %i pennies)\n", coins, quarters, dimes, nickels, pennies);
}
else
{
printf("Error\n");
}
}
}
You can't really compare a float point number to a integer ( 0 ) because some of the deep assembly mechanism
What you can do:
Simply do printf("You need %i coins\n", coins) without condition
Do
if (owed <= 0.001 && owed >= -0.001)
{
printf("You need %i coins\n", coins);
}
It's actually a quite common practice
Thank you everyone for your help. I ended up following Tardis' suggestion, and utilizing integers for the calculations instead. It was a success! Heres the code I ended up with:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main (void)
{
printf("How much change is needed?\n");
float tmp = get_float() * 100;//Gets amount owed from user in "x.xx" format
int owed = round(tmp);
int coins = 0; //Sets initial value of the coins paid to 0
//While loops subtracting one coin from change owed, and adding one to coin count
while (owed >= 25)
{
owed = owed - 25;
coins = coins + 1;
}
while (owed >= 10)
{
owed = owed - 10;
coins = coins + 1;
}
while (owed >= 5)
{
owed = owed - 5;
coins = coins + 1;
}
while (owed >= 1)
{
owed = owed - 1;
coins = coins + 1;
}
//While loops done, now print value of "coins" to screen
if (owed == 0)
{
printf("You need %i coins\n", coins);
}
else
{
printf("Error\n");
}
}
Love the feeling of finally getting a program right. Just wish I had been able to come up with this on my own:/ Nevertheless, thanks everyone for your suggestions.
I wrote a code for greedy algorithm of cs50. It works for inputs between 0 and 1. How can I make it work to inputs like 4.2 , 6.5 , 8 etc?. I have listed my code below. What should I modify in the program?
#include<stdio.h>
#include<cs50.h>
#include<math.h>
int main()
{
int count , change;
float cents;
printf("Enter the change amount : ");
cents = GetFloat();
cents = cents * 100;
change = round(cents);
count = 0;
while(cents < 0 )
{
printf("Enter a positive number : ");
cents = GetFloat();
}
while (change >= 25)
{
change = change - 25;
count++;
}
while (change < 25 & change >= 10)
{
change = change - 10;
count++;
}
while (change < 10 & change >= 5)
{
change = change - 5;
count++;
}
while (change < 5 & change >= 1)
{
change = change - 1;
count++;
}
printf("Total number of coins used : " );
printf (" %d " , count );
printf("\n");
}
I believe that your problem is that you are using bitwise logical operators. You should use && in your comparisons to compare the values of two expressions. There are other little issues: The loop that guarantees positive input should multiply cents by 100 and round(), before assigning this new value to change. But you don't actually need both change and cents. And you don't need as many comparisons as you have written, and without the extra comparisons, you don't need the logical operators that were causing you trouble in the first place!
Edit
I noticed that a number like 4.20 was being rounded first, then multiplied by 100! Of course this is wrong, giving the same results for 4.20, 4.75, and 4. I changed the code below accordingly, but your original code was doing this part correctly (except in the input validation loop, as mentioned earlier). Now the program correctly handle such inputs.
Here is a cleaned-up version (I don't have the cs50.h library, so there are some small differences):
#include <stdio.h>
#include <math.h>
int main(void)
{
int count;
float cents;
printf("Enter the change amount: ");
scanf("%f", ¢s);
cents = (float)round(cents * 100);
count = 0;
while (cents < 0) {
printf("Enter a positive number: ");
cents = (float)round(cents * 100);
}
while (cents >= 25) {
cents -= 25;
count++;
}
while (cents >= 10) {
cents -= 10;
count++;
}
while (cents >= 5) {
cents -= 5;
count++;
}
while (cents >= 1) {
cents -= 1;
count++;
}
printf("Total number of coins used: %d\n", count);
return 0;
}
**I've done a few changes and i'd just like to know if you can help me find out why it isn't running. When I run it the text is printed but the input never stops running. **
The program is meant to replicate(?) the greedy algorithm. It first asks the user how much change is owed and then provides the minimum number of coins with which said change can be made.
I'd greatly appreciate any help you can give with my code.
#include <stdio.h>
#include <math.h>
int main(void)
{
//declared variables
float change;
int num = 0;
// prompts for amount owed
printf("Please provide the amount owed: ");
change = GetFloat();
while (change != 0)
change = change * 100;
int owed = round(change);
{
// if statements for calculating number of coins required
if (owed >= 25)
{
owed = owed - 25;
num ++;
}
if (owed >= 10 && owed < 25)
{
owed = owed - 10;
num ++;
}
if (owed >= 5 && owed < 10)
{
owed = owed - 5;
num ++;
}
if (owed >= 1 && owed < 5)
{
owed = owed - 1;
num ++;
}
}
printf("%d\n", num);
}
When I alter the while statement and comment out the 'change = change * 100;'
it starts to work. However, in doing so the round function won't execute.
change = GetFloat() * 100;
while (change != 0)
// change = change * 1000;
// int owed = round(change);
To my understanding, the part
while (change != 0)
change = change * 100;
is an infinite loop if it is started when change is nonzero. Depending on the platform, eventually NaN or positive infinity is reached by the multiplication, causing the loop to continue forever.
I'm trying to write a code for a bill changer where the amount of money inserted are converted back into coins for the user. The problem is I keep having decimals in my amount of 50c like 222.222 when i input 111.111. My 20c and 10c is unused.. Please help
#include <stdio.h>
int main()
{
double sum50c=0, sum20c=0, sum10c=0, remainder, remainder2, remainder3, end=0;
double amount;
do
{
printf("Please enter an amount(dollars):");
scanf("%lf", &amount);
amount=amount*100;
if(amount<0){
printf("Invalid Input\n");
printf("Re-enter your amount:");
scanf("%lf", &amount);
}
if(amount>=50){
remainder=amount/50;
sum50c=remainder;
}else
if(remainder!=0){
remainder2=remainder/20;
sum20c=remainder2;
}else
if(remainder2!=0){
remainder3=remainder3/10;
sum10c=remainder3;
}
if(sum50c>200||sum20c>200||sum10c>200){
end++;
}else{
end=0;
}
}
while(end<=0);
printf("The amount of 50cents=%lf, 20cents=%lf, 10cents=%lf", sum50c, sum20c, sum10c);
}
There are basically two errors in your code:
Don't operate on floating-point numbers here. The number of coins will be a discrete number, which should be represented as int or maybe even unsigned int. The amount itself may be read in as floating-point number for simplicity, but it should also be converted to the number of cents as integerin order to avoid rounding errors.
You have to find combinations of coins: 30c is 1%times;20c + 1×10c. That means that you can't use else if chains, which will only consider one type of coin. Treat all types of coin, highes denomination first, and then reduce the amount still to handle. Note that with 10c as smallest coin, you might not be able to give full change for all amounts.
Here's you example without the outer loop and without the strange end business:
#include <stdlib.h>
#include <stdio.h>
int main()
{
int num50c = 0,
num20c = 0,
num10c = 0;
int amount; // amount in cents
double iamount; // input amount in dollars
printf("Please enter an amount: ");
scanf("%lf", &iamount);
amount = iamount * 100 + 0.5;
if (amount < 0) {
printf("Invalid Input\n");
exit(1);
}
num50c = amount / 50;
amount %= 50;
num20c = amount / 20;
amount %= 20;
num10c = amount / 10;
amount %= 10;
printf("%d x 50c = %d\n", num50c, num50c * 50);
printf("%d x 20c = %d\n", num20c, num20c * 20);
printf("%d x 10c = %d\n", num10c, num10c * 10);
printf("Remainder: %dc\n", amount);
return 0;
}
To force amount to have integer values you should round the value after your division:
if(amount>=50)
{
remainder=round(amount/50);
sum50c=remainder;
}
I am writing a function for class that takes an amount of money and tells the user how many coins add up to that amount. I seem to have everything working just fine, except pennies. My loop will sometimes stop short and break before adding the proper amount. It usually will stop 1 penny short, but sometimes it will give me the proper answer (one value I have found that gives the correct answer is .09). I've tried changing the float to a double, and I have the same issue. I am pulling my hair out trying to figure out what I am doing wrong.
void change(float total)
{
int quarters, dimes, nickels, pennies;
quarters = 0;
dimes = 0;
nickels = 0;
pennies = 0;
printf("\nTotal value entered: %.2f", total);
while (total >= .25)
{
quarters += 1;
total -= .25;
}
while (total >= .10)
{
dimes += 1;
total -= .10;
}
while (total >= .05)
{
nickels += 1;
total -= .05;
}
while (total >= .01)
{
pennies += 1;
total -= .01;
}
printf("\nQuarters: %d \nDimes: %d \nNickels: %d \nPennies: %d\n\n", quarters, dimes, nickels, pennies);
}
It's almost certainly caused by the limited precision of floating point numbers.
You'll probably find that you're reaching a point where the remaining value is something like 0.009999942 rather than 0.1 and that's why you're exiting early.
But it can show itself even before you reach pennies, if you end up with something like 0.249999 left, which should be a quarter but precision limits may force down to two dimes and four pennies.
As to solving it, I'd get the floating point value rounded to an integer as quickly as possible (multiplying it by a hundred beforehand of course), then you don't have to worry about floating point precision.
You can do this with something like:
int itotal = total * 100 + 0.2;
then using itotal for your calculations:
while (itotal >= 25) {
quarters++;
itotal -= 25;
}
// and so on ...
I had a similar question a while back for one of my labs. Instead of a a while loop for each coin denominations, i had a single do..while with cascaded if statements. In my case the max cost of an item was $1, and I opted to work in ints, but you can format the final output later.
int price, remainder, quarters, dime, nickel, pennies;
printf("Enter the price of the item you bought:>");
scanf("%d", &price);
remainder = 100 - price;
do {
if (remainder >= 25)
{
quarters++;
remainder -= 25;
}
else if (remainder >= 10)
{
dime++;
remainder -= 10;
}
else if (remainder >= 5)
{
nickel ++;
remainder -=5;
}
else if (remainder >= 1)
{
pennies ++;
remainder -=1;
}
} while (remainder > 0);
printf("\nYour change will be dispensed as:\n Quarters: %d \n Dimes: %d \n Nickel: %d \n Pennies: %d \n\n", quarters, dime, nickel,pennies);
Hope it helps.
Floating point math is not exact. See http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html
Floating point math is very complex and subject to many common mis expectations. Try converting your math to using int, and later translate it back.
As you are comparing float which subjected to be full of errors so you can use a roundof function and change the floating point number to integer.
int_total = round( total * 100.0 ); //include math.h
Now, change the loop as,
while (total >= 25)
{
quarters += 1;
total -= 25;
}