My aim with this program is to tell how many coins of each denomination should be given to a customer with the assumption of inputs being from 5-95.
I have written my program in the best modular form I can, and it seems to be working. However, the program shows 0 for each denomination.
What is the problem?
void PrintDisplay(void)
{
printf("Enter an amount to calculate change: ");
return;
}
int GetChange(void)
{
int change;
scanf("%d%*c", &change);
return(change);
}
int GetCoins(int cents, int coin)
{
int quantity;
quantity = cents / coin;
return(quantity);
}
int GetNewChange(int cents, int coin)
{
int newchange;
newchange = cents - coin;
return(newchange);
}
void PrintResult(int fifties, int twenties, int tens, int fives)
{
printf("The amount of each coin denomination you should give are: \n");
printf("Fifty cent coins: %d \n", fifties);
printf("Twenty cent coins: %d \n", twenties);
printf("Ten cent coins: %d \n", tens);
printf("Five cent coins: %d \n", fives);
return;
}
int main(int input)
{
int FiftyCentAmount;
int TwentyCentAmount;
int TenCentAmount;
int FiveCentAmount;
PrintDisplay();
GetChange();
FiftyCentAmount = GetCoins(input, 50);
GetNewChange(input, 50);
TwentyCentAmount = GetCoins(input, 20);
GetNewChange(input, 20);
TenCentAmount = GetCoins(input, 10);
GetNewChange(input, 10);
FiveCentAmount = GetCoins(input, 5);
GetNewChange(input, 5);
PrintResult(FiftyCentAmount, TwentyCentAmount, TenCentAmount, FiveCentAmount);
system("pause");
return(0);
}
A function has an input (the parameters), an output (return value and maybe parameters passed by pointer) and an algorithm that generates the output from the input.
Sometimes function do not really have an input or output like your superflous PrintDisplay. This is generally okay if you make your code more readable/ better organized that way. Your function is superflous because you make a function (which has four lines) for a simple one line statement. Not inherently bad but superflous.
The return value "appears" at the position where the function call was made. So if you do
input = GetChange();
input will be set to the return value of GetChange.
You fixed this after Daves answer, but didn't see that all your Get... functions also have a return value you just ignore in your code.
So by fixing all of them your code should work (or not see edit).
All your functions (except PrintResult and the textinput) are basically oneliners. And
They reduce to
int GetCoins(int cents, int coin)
{
return cents / coin;
}
int GetNewChange(int cents, int coin)
{
return cents - coin;
}
So an improved program (in your design) would look like this then:
int main()
{
int leftover_change;
printf("Enter an amount to calculate change: ");
leftover_change= GetChange();
int FiftyCentAmount = GetCoins(leftover_change, 50);
leftover_change = GetNewChange(leftover_change, 50);
int TwentyCentAmount = GetCoins(leftover_change, 20);
leftover_change = GetNewChange(leftover_change, 20);
int TenCentAmount = GetCoins(leftover_change, 10);
leftover_change = GetNewChange(leftover_change, 10);
int FiveCentAmount = GetCoins(leftover_change, 5);
leftover_change = GetNewChange(leftover_change, 5);
PrintResult(FiftyCentAmount, TwentyCentAmount, TenCentAmount, FiveCentAmount);
if(leftover_change >0)
{
printf("there are %d cents left\n", leftover_change);
}
system("pause");
return 0;
}
This still vioaltes the DRY concept (Dont repeat yourself) you could fix this (at least partially) by replacing the magic numbers with defines or const variables.
Even better would be a loop that iterates through the different coins. But this needs a bit more thinking and the use of arrays.
edit: I did not check the algorithm in the first place, and my scanfreduction was bullshit but I was in a hurry so here a version that works. To make this answer complete, but as Dave said you should check your algorithm before you implement it.
int GetNewChange(int cents, int coin)
{
return cents % coin; //this is the modulus operator
}
GetChange() returns the user's input, but you aren't saving the result of the call. You want
input = GetChange();
Related
Im a complete newbie in programming.
I've been instructed to write the program above in the title.
I'm here seeking help from everyone to help me understand and code better.
Can anyone tell me what is wrong with my code? i cant get it to exit the loop
more detailed information on the program:
You are asked to write a simple C program that will accept an integer value in the range
of 5-95 and as a multiple of 5 representing the number of cents to give to a customer in
their change. The program should calculate how many coins of each denomination and
display this to the user. Valid coin values are 50, 20, 10 and 5. Your solution (program
and algorithm) should be modular in nature.
/*This program acts as a coin changer that helps to provide
change user their changes in the highest amount.
*/
#include <stdio.h>
// Delcaration of functions
int coins(int fifty, int twenty, int ten, int five);
int main()
{
// Declare and initialize working storage
int fifty = 0;
int twenty = 0;
int ten = 0;
int five = 0;
int user_input = 0;
int counter = 3;
int coins(int fifty, int twenty, int ten, int five);
// Prompt user for input, prints, and loops for 3 attempts
while (counter > 0)
{
printf("\nPlease enter an amount within the range of 5 to 95\n");
printf("\nPlease enter the amount you wish to change: \n\n");
scanf("%d", &user_input);
if ((user_input < 5) || (user_input > 95))
{
printf("\nInvalid input\n");
printf("\nNumber of attemps: %d\n\n\n\n", counter);
}
counter--;
}
printf("\nYou have exceeded the number of attempts\n");
// Compute number of coins to be given
fifty = user_input / 50;
twenty = user_input / 20;
ten = user_input / 10;
five = user_input / 5;
if (fifty >= 1)
{
printf("\nNumber of fifty cent coins are: %d\n", fifty);
}
else if (twenty >= 1)
{
printf("\nNumber of twenty cent coins are: %d\n", twenty);
}
else if (ten >= 1)
{
printf("\number of ten cent coins are: %d\n", ten);
}
else if (five >= 1)
{
printf("\nNumber of five cent coins are: %d\n", five);
}
return 0;
}
Here is a program that does what you ask. This program could still be improved vastly.
#include <stdio.h>
// Delcaration of functions
int coinReturn(int coinSize, int value)
{
int tmp = 0;
while(value >= coinSize)
{
value-=coinSize;
tmp++;
}
printf("Number of %i cent coins are: %d\n", coinSize,tmp);
return value;
}
int main()
{
// Declare and initialize working storage
int user_input = 0;
int remainingValue;
// Prompt user for input, prints, and loops for 3 attempts
while (1)
{
printf("\nPlease enter an amount within the range of 5 to 95\n");
printf("\nPlease enter a multiple of 5\n");
printf("\nPlease enter the amount you wish to change: \n");
scanf("%d", &user_input);
if ( (user_input < 5 || user_input > 95) || (user_input % 5 != 0))
{
printf("\nInvalid input!\n");
}
else
{
break;
}
}
//Calculate and Print Output
remainingValue = coinReturn(50,user_input);
remainingValue = coinReturn(20,remainingValue);
remainingValue = coinReturn(10,remainingValue);
remainingValue = coinReturn(5,remainingValue);
return 0;
}
I would focus on a couple things if I were you and make sure I learned the concept. These are:
- Break Statements
- Function Declarations and function Definitions
- Modulo
- Flowcharting
This problem can be slightly tricky and flowcharting it when you start is your best bet.
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;
}
Program (in C) is to ask user to input integers one at a time (0 is quit indication) and find the number and total of the even inputs/odd inputs using while loop, if/else structure, and user defined function. I can't get the user defined function to print the statements needed.
(Code so far below)
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
char name[30];
printf("Enter name: ");
scanf("%s", name);
int num=1, even_count=0, even_sum=0, odd_count=0, odd_sum=0;
while (num != 0)
{
printf("Enter an integer (0 to stop): ");
scanf("%d", &num);
}
if ((num % 2) == 0) {
even_count++;
}
else {
odd_count++;
}
printf("%s,your inputs are broken down as follows: \n", name);
return even_count, even_sum, odd_count, odd_sum;
}
int output_function(int even_ct, int e_sum, int odd_ct, int o_sum)
{
int count1, sum1, count2, sum2 = main();
printf("You entered %d even numbers with a total value of %d.\n", count1, sum1);
printf("You entered %d odd numbers with a total value of %d.\n", count2, sum2);
return 0;
}
You never call output_function.
Replace
return even_count, even_sum, odd_count, odd_sum;
by
output_function(even_count, eve_sum, odd_count, odd_sum);
and remove
int count1, sum1, count2, sum2 = main();
The last line to remove makes absolutely no sense.
and finally replace your printfs by this:
printf("You entered %d even numbers with a total value of %d.\n", even_ct, e_sum);
printf("You entered %d odd numbers with a total value of %d.\n", odd_ct, o_sum);
I think, first you should declare the output_function before the main:
int output_function(int even_ct, int e_sum, int odd_ct, int o_sum);
int main()
{...}
Second, the return value of the main must be a single integer value.
Third, the output_function return always a zero.
And don't forget to call the output_function.
SK
You have some nice thoughts.
You thought:
output_function is defined after main so it can call main
A function can return several variables which in order:
return even_count, even_sum, odd_count, odd_sum;
And you can get the value of them by calling the function:
int count1, sum1, count2, sum2 = main();
But C does not work like that:
main function is executed the very first, earlier than any other functions.
You cannot return several variables like that in C (in some other high level languages like Python, it is ok).
return even_count, even_sum, odd_count, odd_sum; equals to return odd_sum;
Similar above point, int count1, sum1, count2, sum2 = somethings; just bring you sum2 = somethings
Please clean these mess first and you might get the program work well.
I'm writing a program for my CS239 class in C that asks for cost of something, amount paid, calculates tax, and then determines what type of change to return and optimal coins to return.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
void coinage(int c, int q, int d, int n, int p); //change calculation function
int main(void)
{
double price, tax, paid, due, t_back; //used double instead of int for decimal purpose
int c, b, q, d, n, p; //change, bills, quarters, dimes, nickels, pennies
printf("\nProgram Author: PuppyBreath\n");
printf("\nEnter price in dollars: $");
scanf("%lf", &price);
tax = 1.06;
due = price*tax;
printf("Sales tax in Kentucky is 6%, therefore the amount due is $%.2f. \n", due);
printf("Enter amount paid: \n");
scanf("%lf", &paid);
paid = paid*100+0.5;
due = due*100;
c = paid-due;
b = c/100;
t_back = (paid-due)/100-0.01; //used a double rather than an int for increased precision
coinage(c, q, d, n, p); //calls coinage function
printf("Change back:\n");
printf("Total: $%.2f\n", t_back);
if(t_back >= 1)
printf("Ones: %d\n", b);
else
printf("No bills\n");
if(q >= 1)
printf("Quarters: %d\n", q);
else
printf("NO QUARTERS FOR YOU!\n");
if(d >= 1)
printf("Dimes: %d\n", d);
else
printf("NO DIMES FOR YOU!\n");
if(n >= 1)
printf("Nickels: %d\n", n);
else
printf("NO NICKELS FOR YOU!\n");
if(p >= 1)
printf("Pennies: %d\n", p);
else
printf("NO PENNIES FOR YOU!\n");
return 0;
}
void coinage(int change, int quarters, int dimes, int nickels, int pennies)
{
int t_change, t_quarters, t_dimes, t_nickels, t_pennies;
t_change = change%100; //use mod to carry remainders and dividing to find number of each coin
t_quarters = t_change/25.00;
t_change = t_change%25;
t_dimes = t_change/10.00;
t_change = t_change%10;
t_nickels = t_change/5.00;
t_change = t_change%5;
t_pennies = t_change+0.5;
quarters = t_quarters;
dimes = t_dimes;
nickels = t_nickels;
pennies = t_pennies;
}
This is my code, and after I compile it this is what happens: (the '8' and '10' are my inputs)
./a.out
Program Author: PuppyBreath
Enter price in dollars: $8
Sales tax in Kentucky is 6%, therefore the amount due is $8.48.
Enter amount paid:
10
Change back:
Total: $1.51
Ones: 1
NO QUARTERS FOR YOU!
NO DIMES FOR YOU!
Nickels: 4195472
NO PENNIES FOR YOU!
As you know, if your change is $1.51 (supposed to be $1.52 but thats another slightly smaller fish) then you definitely don't need 4,195,472 nickels. Why is this happening? Thanks in advance! I'm not extremely experienced in this, I'm only 3 weeks into any C programming, be gentle!
void coinage(int change, int quarters, int dimes, int nickels, int pennies)
Remember that in C, all arguments are passed by value, thus anything you modify in this function, aren't modified in the out world.
Change it to take pointers to simulate pass-by-reference, the signature should look like this, the body should be modified accordingly.
void coinage(int change, int *quarters, int *dimes, int *nickels, *int pennies)
The core problem here is that the coinage function is designed to return multiple values but the writer has not yet learned good ways of doing so.
One alternative is to redesign the interface so that the coinage function only returns one value, but gets called several times. One could make it take three parameters, the amount of change, the denomination of the current coin, and the denomination of smallest coin with higher value than current. It would return a simple int representing the count for the current coin. The existing coinage function effectively contains this as a block of code that is repeated with only changes in the numbers, not what it is doing.
In the main function variables such as q would be replaced by the expression coins(c, 25, 100), meaning the number of 25 unit coins for change amount c given existence of 100 unit coins or bills.
I have an assignment that asks us to code an automatic change program for a dollar input up to $200.00. Basically, someone inputs an amount and the output displays that amount in change for the various following denominations (how many 20s, 10s, 5s, 1s, quarters, dimes, nickels, and pennies).
I've worked out a way to do this with if/else statements for each denomination (see below), but I was wondering if there was an easier, more condensed way to execute this with loops? (it's an intro course, so we're not yet at functions/arrays, etc.)
int twenties; int tens;
int fives;
int ones;
int quarter;
int dime;
int nickel;
int penny;
double dollar_ent;
printf("Please enter a dollar amount up to 100: ");
scanf("%lf", &dollar_ent);
printf("Name - Assignment 2 - Change-O-Matic\n\n");
printf("Amount entered: $%.2lf\n\n", dollar_ent);
twenties = (dollar_ent / 20);
if (twenties >=2)
printf("%.0d\t$20.00's\n", twenties);
if (twenties == 1)
printf("%.0d\t$20.00\n", twenties);
else
printf("");
Thanks!
it’ll be easier for you to convert amount into cents.
then you’ll have an integer like 20000 ($200).
have an array of all possible denominations :
int denominations[] = { 2000, 1000, 500, 100, 25, 10, 5, 1}.
then iterate through this array.
divide current amount by current denomination and subtract it from current sum. Compute rest of the division and set it as current sum, then move to next denomination … and so on...
Yes, it is easier to do with a loop. But you'll need an array to go with it:
#include <stdio.h>
static int denoms[] = {
2000,
1000,
500,
100,
25,
10,
5,
1,
0
};
int main () {
double dollar_ent;
int i;
int twenties;
printf("Please enter a dollar amount up to 100: ");
scanf("%lf", &dollar_ent);
printf("Name - Assignment 2 - Change-O-Matic\n\n");
printf("Amount entered: $%.2lf\n\n", dollar_ent);
dollar_ent *= 100;
for(i = 0; denoms[i]; i++) {
twenties = (dollar_ent / denoms[i]);
if (twenties >=2)
printf("%.0d\t$%.02f's\n", twenties, denoms[i] / 100.);
if (twenties == 1)
printf("%.0d\t$%.02f\n", twenties, denoms[i] / 100.);
dollar_ent -= twenties * denoms[i];
}
}
The lesson is this: if you have a program that looks like this:
some code with one value;
similar code with another value;
similar code with yet another value;
Consider replacing it with a loop:
for ( some expression that takes on each value in turn ) {
the identical code, with the values replaced by variables;
}
Not as you have written it. But as you've written it it only finds the number of 20s.