So I'm trying to make a code for one of my classes, and for some reason when I try to compile it, it simply won't accept the subtraction sections. Does anyone know what's going on?
Here's the code:
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void) {
float value;
do {
value = get_float("enter value: ");
} while (value >= 0);
value * 100;
int quarter = 25;
int dime = 10;
int nickel = 5;
int penny = 1;
if (value >= quarter) {
while (value >= quarter) {
quarter - value;
}
int quarters = 0;
quarters++;
} else {
while (value >= dime) {
dime - value;
}
int dimes = 0;
dimes++;
} else {
while (value >= nickel) {
nickel - value;
}
int nickels = 0;
nickels++;
} else {
while (value >= penny) {
penny - value;
}
int pennies = 0;
pennies++;
}
printf ("%i pennies, %i nickels, %i dimes, %i quarters\n", pennies, nickels, dimes, quarters);
}
and whenever I try to compile it, it says cash.c:25:20: error: expression result unused [-Werror,-Wunused-value] quarter - value; or any of the other math expressions. I haven't been able to compile it so, if this doesn't work, I would like a heads up. thanks, guys.
There are multiple issues in you code:
the do / while loop continues as long as the entered value is >= 0. This is the exact opposite of what you want. You should continue if the value is negative.
the statements value * 100; and dime - value;... do not have any side effects, as diagnosed by the compiler. You should write value *= 100; or value = value * 100; etc.
multiplying the float value by 100 might not produce an integer because of the limited precision of the floating type and its inability to represent multiples of 0.01 exactly. You should round the value to the nearest integer with value = round(value * 100);
the series of else clauses prevent proper computation of the change to give. As coded, you can only give one kind of coin, and only one of that.
the variables quarters, dimes, nickels and pennies are defined with a local scope that ends before the final printf statement, so they are undefined there and the compiler produces an error.
You can compute the number of quarters with int quarters = floor(value / 25); etc.
Here is a modified version:
#include <cs50.h>
#include <math.h>
#include <stdio.h>
int main(void) {
float value;
do {
value = get_float("enter value: ");
} while (value < 0);
value = round(value * 100);
int quarters = floor(value / 25);
value -= 25 * quarters;
int dimes = floor(value / 10);
value -= 10 * dimes;
int nickels = floor(value / 5);
value -= 5 * nickels;
int pennies = value;
printf ("%i pennies, %i nickels, %i dimes, %i quarters\n", pennies, nickels, dimes, quarters);
return 0;
}
Using integer arithmetic to split value into coins allows for simpler code, using the modulo operator %:
#include <cs50.h>
#include <math.h>
#include <stdio.h>
int main(void) {
float value;
do {
value = get_float("enter value: ");
} while (value < 0);
int cents = round(value * 100);
int quarters = cents / 25; cents %= 25;
int dimes = cents / 10; cents %= 10;
int nickels = cents / 5; cents %= 5;
int pennies = cents;
printf ("%i pennies, %i nickels, %i dimes, %i quarters\n", pennies, nickels, dimes, quarters);
return 0;
}
Related
This is the code that I am trying to test.
I have tried multiple times to change the type of loop that I used or to even change where I placed it (either in the "int get_cents" function or where it is now).
Could it be that because I am using a do while loop - the code doesn't initially reject the negative inputs and that is the reason why when I run check50 - I get this result:
running ./cash_test 0...
sending input -10...
checking that input was rejected...
#include <cs50.h>
#include <stdio.h>
int get_cents(void);
int calculate_quarters(int cents);
int calculate_dimes(int cents);
int calculate_nickels(int cents);
int calculate_pennies(int cents);
int main(void)
{
// Ask how many cents the customer is owed
int cents;
do
{
cents = get_cents();
}
while (cents < 1);
{
// Calculate the number of quarters to give the customer
int quarters = calculate_quarters(cents);
cents = cents - quarters * 25;
// Calculate the number of dimes to give the customer
int dimes = calculate_dimes(cents);
cents = cents - dimes * 10;
// Calculate the number of nickels to give the customer
int nickels = calculate_nickels(cents);
cents = cents - nickels * 5;
// Calculate the number of pennies to give the customer
int pennies = calculate_pennies(cents);
cents = cents - pennies * 1;
// Sum coins
int coins = quarters + dimes + nickels + pennies;
// Print total number of coins to give the customer
printf("%i\n", coins);
}
}
int get_cents(void)
{
// TODO
return get_int("how many cents? ");
}
int calculate_quarters(int cents)
{
// TODO
return cents/25;
}
int calculate_dimes(int cents)
{
// TODO
return cents/10;
}
int calculate_nickels(int cents)
{
// TODO
return cents/5;
}
int calculate_pennies(int cents)
{
// TODO
return cents/1;
}
Why is my code working well only when I test it manually?
From the narrative of the error you get from the checker application, it appears that the requirement of the test is that the program is supposed to immediately indicate that an invalid negative value was entered and the program is supposed to end. Instead of a "while" loop where a retry is allowed, you might try the following code snippet.
// Ask how many cents the customer is owed
int cents;
cents = get_cents();
if (cents < 0)
{
printf("A negative value was entered and rejected\n");
return -1;
}
This would result in an output as follows if a value of "-10" were entered.
#Una:~/C_Programs/Console/cash_test/bin/Release$ ./cash_test
how many cents? -10
A negative value was entered and rejected
#Una:~/C_Programs/Console/cash_test/bin/Release$
You might give that a try.
The get_cents function here will not reprompt if a negative number is entered because that test is in main. It is explicit in the spec that the reprompt should be within the get_cents function:
Implement get_cents in such a way that the function prompts the user for a number of cents using get_int and then returns that number as an int. If the user inputs a negative int, your code should prompt the user again.
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;
}
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 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;
}
I can't figure out why this works for 90% of the inputs, but not the others. It is meant to tell you how many coins you would get back in change. Most test amounts work fine, but if you enter 4.20 (or $4.20), it returns 23 coins... it should be 18 coins (16 quarters and 2 nickels). Where is the bug? Here is my code:
#include <stdio.h>
#include <cs50.h>
int main(void){
float change = 0.00;
printf("How much change is owed? ");
change = GetFloat();
float quarters = change/.25;
change-= (int)quarters*.25;
float dimes = change/.10;
change-= (int)dimes*.10;
float nickels = change/.05;
change-= (int)nickels*.05;
float pennies = (change+.005)/.01;
change-=(int)pennies*.01;
int total = (int)quarters+(int)dimes+(int)nickels+(int)pennies;
printf("%d\n", total);
return 0;
}
The closest float value to 4.20 is slightly smaller than that (4.19999980926513671875, for the usual 32-bit IEEE754 floats). So after you subtracted the $4 from the 16 quarters, you have an amount left that is slightly smaller than 0.2. Dividing that by 0.1 results in a value slightly smaller than 2, so your nickels value is 1. The same happens then after you subtract your nickel, the value is slightly smaller than 0.1, dividing by 0.05 results in a quotient slightly smaller than 2.
You should use integers only for such a computation, calculating in cents.
Throw out the floating-point calculations. this is all based on hundredths at best, so just use integer division/modulo. Never rely on perfect accuracy in floating point numbers.
#include <stdio.h>
#include <cs50.h>
int main(void){
float fchange = 0.00;
int change = 0;
printf("How much change is owed? ");
fchange = GetFloat();
change = (int)roundf(fchange*100.0);
int quarters = change/25;
change = change % 25;
int dimes = change/10;
change = change % 10;
int nickels = change/5;
change = change % 5;
printf("%d quarters, %d dimes, %d nickels, %d pennies\n", quarters, dimes, nickels, change);
return 0;
}
The other answers have it mostly covered: you should be working with fixed point here, not floating point. Be careful to round properly when going from the floating point input to your fixed point representation, though. Here is a short version I hacked up, which should work for all positive inputs:
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char ** argv)
{
float change = atof(argv[1]);
int work = (int)(100*change+0.5);
int quarters, dimes, nickels, pennies;
quarters = work/25; work %= 25;
dimes = work/10; work %= 10;
nickels = work/5; work %= 5;
pennies = work;
printf("%.2f dollars = %d quarters, %d dimes, %d nickels and %d pennies: %d coins total\n",
change, quarters, dimes, nickels, pennies, quarters+dimes+nickels+pennies);
return 0;
}
For example:
./change 4.20
4.20 dollars = 16 quarters, 2 dimes, 0 nickels and 0 pennies: 18 coins total