New programmer, I need help on greedy.c from Harvard CS50 - c

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.

Related

CS50 Pset1 cash code not working properly

So I just started with the cs50 course and I'm doing the 1 problem set with greedy algorithms. When I run the program it will ask the question right, when I answer it doesn't give output. I can't tell what's wrong.
Here's the code
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main (void)
{
float n;
int cents;
int coins = 0;
// Prompt user for amount owed
do
{
n = get_float("Change owed?:");
}
while (n < 0);
// convert input into cents
cents = round(n * 100);
//loop for minimum coins
while (cents >= 25)
{
cents = cents - 25;
coins++;
}
while (cents >= 10)
{
cents = cents - 10;
coins++;
}
while (cents >= 5)
{
cents = cents - 5;
coins++;
}
while (cents >= 1)
{
cents = cents - 1;
coins++;
//Print number of coins
printf("%i\n", coins);
}
}
You have your print method inside a while-loop, which if its condition evaluates to false, won't execute its body.
What happened is that nothing would get printed, unless cents would be greater or equal to 1 when reaching your last while-loop.
Change this:
while (cents >= 1)
{
cents = cents - 1;
coins++;
//Print number of coins
printf("%i\n", coins);
}
to this:
while (cents >= 1)
{
cents = cents - 1;
coins++;
}
//Print number of coins
printf("%i\n", coins);
With this change, the print method will execute, regardless of whether the code flow enters the last while-loop or not.

IF condition not working as expected - C Language

I have the below code in which the if condition does not seem to be working as expected.
as an example, if I enter 0.29 the results that are given are
Quarters: 1
Dimes: 0
Nickels: 4205264
Pennies: 4
As you can see this is incorrect as after the first if statement is performed 'if (cents >= 25)' this would leave a remainder of 4 which is stored in the 'cents' variable. This should mean that the next two 'IF' statements return a '0' and the final if statement is carried out 'if (cents >= 1)'. This is however not the case as you can see that Nickles is returning a value of 4205264.
When you enter 1.17 the result returns as expected:
Quarters: 4
Dimes: 1
Nickels: 1
Pennies: 2
#include <cs50.h>
#include <math.h>
#include <stdio.h>
int main(void)
{
float dollars;
int cents;
int quartersUsed;
int dimesUsed;
int nickelsUsed;
int penniesUsed;
do
{
dollars = get_float("Float: ");
while (dollars <= 0) {
dollars = get_float("Float: ");
}
cents = roundf(dollars * 100);
printf("%i\n", cents);
if (cents >= 25) {
quartersUsed= cents / 25;
cents = cents % 25;
}
if (cents >= 10) {
dimesUsed = cents / 10;
cents = cents % 10;
}
if (cents >= 5) {
nickelsUsed = cents / 5;
cents = cents % 5;
}
if (cents >= 1) {
penniesUsed = cents / 1;
cents = cents % 1;
}
printf("Quarters: %i\n",quartersUsed);
printf("Dimes: %i\n",dimesUsed);
printf("Nickels: %i\n",nickelsUsed);
printf("Pennies: %i\n",penniesUsed);
}
while (dollars == false);
}
You need to initialize your variables, because if you don't enter in a if block, what is happening in your example, you end printing a variable that has been never intialized.
In C, no intialization is done for you so if you don't put a value in your variable, they will have an undefined value (depending on which value was there previously in memory).
Note that your if clauses not only are unnecessary, as they also may let some of your variables to be printed uninitialized (which is probably what is causing the problem in your output). And just as you don't need all those condition checks, you don't need all those variables. Remember that C programmers tend to focus on the economy of operations and space whenever possible. Check my implementation below, compare it to yours, and try to guess how many operations and space it saves. (Since you didn't post your "cs59.h" library, I commented it and implemented a "get_float" function that always returns "1.17".)
#include <stdio.h>
#include <math.h>
//#include <cs50.h>
float get_float(const char *)
{
return 1.17;
}
int main()
{
float dollars;
while((dollars = get_float("Float: ")) <= 0);
int cents = (int) roundf(dollars * 100);
printf("%i\n", cents);
printf("Quarters: %i\n", cents / 25);
printf("Dimes: %i\n", (cents = cents % 25) / 10);
printf("Nickels: %i\n", (cents = cents % 10) / 5);
printf("Pennies: %i\n", cents % 5);
return 0;
}

Confused with why code not running correctly

**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.

Need to return a value from a do/while and multiple while loops - C

I am trying to build a simple change calculator of sorts. The user inputs an amount of change owed, and then they press return. The value they entered is supposed to be multiplied by 100 first (so that when we round it, the digits are not truncated). The rounding is supposed to turn the float into an int, and then all the math operations (the while loops) should execute, with a single number printing out at end that represents how many coins they were given (i.e. how many quarters, dimes, etc...) The code compiles fine, it prompts the user to input a value, but then when you press return, nothing is executed, and the command line goes back to being blank.
Any ideas what I'm doing wrong? My guess is the values in the while loops are not getting transferred out of the loop, so they can be used in the next loop. But then I am a very early beginner in C language, and not sure the correct rules for the loops. I tried looking up while loop examples, but nothing really explains exactly how to get a value to carry from one while loop to another. If, in fact, that is the problem. Thanks for your help.
CODE REVISION:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main (void) {
float change;
int cents;
int quarter_count = 0;
int dime_count = 0;
int nickel_count = 0;
int pennies = 0;
int total_count;
do
{
printf("Enter the amount of change you are owed: ");
change = GetFloat();
cents = round(change * 100);
}
while (change < 0);
return cents;
int quarter = 25;
while (cents >= quarter)
{
cents = cents - quarter;
quarter_count++;
}
return cents;
int dime = 10;
while (cents >= dime)
{
cents = cents - dime;
dime_count++;
}
return cents;
int nickel = 5;
while (cents >= nickel)
{
pennies = cents - nickel;
nickel_count++;
}
return pennies;
total_count = quarter_count + dime_count + nickel_count + pennies;
printf("%d\n", total_count);
}
After every while loop you put return statement so. Code after first while..loop meaning less.
Also for third while..loop you put condition like while (cents >= nickel) but in while loop you dont alter value of cents.So it will in infinine loop if cent value remain greater then when it reach upto third while..loop.
See my updated code.It will do basic functionality which may be you want
#include <stdio.h>
#include <string.h>
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main (void) {
float change;
int cents;
int quarter_count = 0;
int dime_count = 0;
int nickel_count = 0;
int pennies = 0;
int total_count;
do
{
printf("Enter the amount of change you are owed: ");
change = GetFloat();
cents = round(change * 100);
}
while (change < 0);
int quarter = 25;
while (cents >= quarter)
{
cents = cents - quarter;
quarter_count++;
}
if (cents <= 0)
goto done;
int dime = 10;
while (cents >= dime)
{
cents = cents - dime;
dime_count++;
}
if (cents <= 0)
goto done;
int nickel = 5;
pennies=cents;
while (pennies >= nickel)
{
pennies = pennies - nickel;
nickel_count++;
}
done:
total_count = quarter_count + dime_count + nickel_count + pennies;
printf("%d\n", total_count);
return 0;
}

Beginner C: can't move on to next loop

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.

Resources