I just took the CS50 course and am struggling with the Pset 1. Here is my code :
#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 = get_cents();
// 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", quarters);
}
int get_cents(void)
{
int owed;
do
{
owed = get_int("Change owed: ");
} while (owed<=0);
return owed;
}
int calculate_quarters(int cents)
{
int n;
while (cents <= 25)
{
n ;
cents = cents - 25;
}
return n;
}
int calculate_dimes(int cents)
{
int n;
while (cents <= 10)
{
n ;
cents = cents - 10;
}
return n;
}
int calculate_nickels(int cents)
{
int n;
while (cents <= 5)
{
n ;
cents = cents - 5;
}
return n;
}
int calculate_pennies(int cents)
{
int n;
while (cents <= 1)
{
n ;
cents = cents - 1;
}
return n;
}
The code returns huge amounts like "277258257".The issue is on the functions but I can't figure out what it is. When I use these same while loops in the main function instead of creating functions, it works perfectly (but then, it doesn't meet the exercise requirement as the CS50 bot also checks if these functions are present in the code).
P.S : sorry for my English, my main language is French and I sometimes say things weirdly. If anything that I said does not make sense please tell me.
CodePudding user response:
In the following
int n;
/* ... */
n
n
is uninitialized, containing an indeterminate value. Sometimes referred to as a garbage value, this value is effectively random. Utilizing this value in n
invokes Undefined Behaviour.
Initialize each variable.
int n = 0;
Each while
loop for calculating the coins is using the wrong operator. Change
while (cents <= 25)
to
while (cents >= 25)
And the same with the others.
coins
is unused. Change
printf("%i\n", quarters);
to
printf("%i\n", coins);