Infinite loop in c due to rounding? - c

The following code is looping infinitely. I believe it may be a rounding issue though not entirely sure.
I am fairly new to C so not sure why I'm getting the infinite looping that I'm getting. The code seems to make sense though keeps looping.
#include <stdio.h>
#include <cs50.h>
#include <math.h>
#include <string.h>
int main(void){
float quarter = .25;
int Qtr = 0;
float dime = .10;
int Dm = 0;
float nickel = .5;
int Nck = 0;
float penney = .01;
int Pn = 0;
float change;
float userInput;
float newspaperCost;
do{
printf("How much is the news paper today: \n");
newspaperCost = GetFloat();
printf("Amount Tendered: ");
userInput = GetFloat();
printf("You entered $%2.2f\n", userInput);
change = userInput - newspaperCost;
printf("Change: $%2.2f\n", change);
}
while(newspaperCost <= 0);
while(change > 0){
printf("%f\n", change);
while(change - quarter > 0){
change = change - quarter;
Qtr++;
}
while(change - dime > 0){
change = change - dime;
Dm++;
}
while(change - nickel > 0){
change = change - nickel;
Nck++;
}
while(change - penney > 0){
change = change - penney;
Pn++;
}
}
printf("Your change consists of %d quarters, %d dimes, %d nickels, and %d pennies\n", Qtr, Dm, Nck, Pn);
} //end main

You have a logic error in the last while loop.
Instead of
while(change - penney > 0){
change = change - penney;
Pn++;
}
Use
while(change > 0){
change = change - penney;
Pn++;
}

Don't use floating point to represent currency.
Prefer double over float unless you have a good reason.
penny*
You're not using any equality operators with floating point operands, so you probably have a logical error.

Your code:
do{
printf("How much is the news paper today: \n");
newspaperCost = GetFloat();
printf("Amount Tendered: ");
userInput = GetFloat();
printf("You entered $%2.2f\n", userInput);
change = userInput - newspaperCost;
printf("Change: $%2.2f\n", change);
} while(newspaperCost <= 0);
Won't exit this loop while newspaperCost <= 0. I'm assuming you aren't inputting a negative number at
printf("How much is the news paper today: \n");
newspaperCost = GetFloat();
That's why you have an infinite loop.

Related

write a program that will accept an integer value in the range of 5-95 and as a multiple of 5

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.

Trying to write a code for a bill changer/coin vending kiosk

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;
}

C. Check input of a float for a certain number of decimal places

Good morning. The code I have written is made to calculate the amount of change given in a transaction, the change portion only, the paper change is ignored. I would like to do an error check to make sure that the user entered # does not exceed 2 decimal places. This is my code.
#include <stdio.h>
#include <stdlib.h>
void intro();
void instructions();
void getvalues(float *owe, float *paid);
float totalchange(float *owe, float *paid);
void quarters (float *change);
void dimes (float *change);
void nickels (float *change);
void pennies (float *change);
int main()
{
float owe = 0.0, paid = 0.0, change;
int a = 2;
intro();
instructions();
printf("Would you like to continue?\n1: Continue\n0: Exit\n");
scanf("%i", &a);
if (a== 0)
exit(0);
while (a == 1){
getvalues(&owe, &paid);
while (owe > paid)
getvalues(&owe, &paid);
change = totalchange(&owe, &paid);
quarters (&change);
dimes (&change);
nickels (&change);
pennies (&change);
printf("Would you like to make another calculation?\n1: Continue\n0: Exit\n");
scanf("%i", &a);
}
return 0;
}
void intro(){
printf("Program: Homework 1 Part 1 :: Change Calculator\nAuthor: Jason Golightly\nDate:5-13-15\nVersion 1.0\n\n");
}
void instructions(){
printf("This program is designed to calculate the coin\nportion of the change given after a purchase.\n");
printf("When prompted, please enter the purchase amount and the amount paid.\nThe amount paid must exceed the purchase amount.\n");
}
void getvalues(float *owe, float *paid){
printf("Please enter the amounts in a dollars.cents fashion\n\nPurchase amount?\n");
scanf("%f", owe);
printf("\nAmount paid?\n");
scanf("%f", paid);
printf("\n");
if (*owe > *paid)
printf("ERROR. Please enter valid amounts.\n");
if (*owe == *paid)
printf("You have given exact change.\n")
}
float totalchange(float *owe, float *paid){
int a;
a = (*paid - *owe)*100;
a = a % 100;
printf("total change = %i\n",a);
return a;
}
void quarters (float *change){
int q;
q = *change / 25;
printf("Quarters = %i\n", q);
*change = *change - 25*q;
}
void dimes (float *change){
int d;
d = *change / 10;
printf("Dimes = %i\n", d);
*change = *change - 10*d;
}
void nickels (float *change){
int n;
n = *change / 5;
printf("Nickels = %i\n", n);
*change = *change - 5*n;
}
void pennies (float *change){
int p;
p = *change / 1;
printf("Pennies = %i\n\n", p);
*change = *change - 1*p;
}
Also, in case you have not noticed, I am fairly new to programming. If you see anything else I could be doing better, please feel free to point it out.
Thanks, Jason
On simple approach to avoid the in-exact floating point calculation is to read the input as a string, parse it into a int, and display it as *.##
i.e.
char number[11];
scanf("%10s", number);
int actual_number = parse(number); // parse the string here.
This actual number is basically dollar*100 + cents - which is an int.
Now perform all the calculations and display like this:
float f = (float)actual_number/100.f ;
printf("%.2f", f);
In the parse routine, you only consider the first two digits after encountering a .
Here is an example of the parse routine in C.

change counter c program not displaying correct output

I am working on a change counter program and I am stuck, I have searched here and 2 other coding forums, google and youtube, but haven't found an answer yet...my program sucks and i am brand new to c/c++...my txt book is not here yet so I am trying to read every every thing i can get my hands on till it gets here
This is what the output should be in the console window:
Welcome to Change Counter by Jo Mama!!
Please enter the total amount of purchase: $52.173
$52.173
Please enter amount of money tendered: $60
$60.00
Your change is: $7.83
-------------------------------------------
Twenties : 0
Tens : 0
Fives : 1
Ones : 2
Quarters : 3
Dimes : 0
Nickels : 1
Pennies : 3
-------------------------------------------
Thank you for using Change Counter!
here is what i have so far...
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(void)
{
// define variables here
long double numberOfTwenties = 0;
long double numberOfTens = 0;
long double numberOfFives = 0;
long double numberOfOnes = 0;
long double numberOfQuarters = 0;
long double numberOfDimes = 0;
long double numberOfNickels = 0;
long double numberOfPennies = 0;
double purchasePrice = 0;
double amountTendered = 0;
double amountOfChange = 0;
double amountOfChangeCents = 0;
// start program here
printf("Welcome to the change counter by Josh Manion!!\n\n");
printf("Please enter the total amount of purchase: $");
scanf("%d", &purchasePrice);
printf("%d\n", purchasePrice);
printf("Please enter amount of money tendered: $");
scanf("%d", &amountTendered);
printf("%d\n", amountTendered);
//do change calculations here
amountOfChange = (amountTendered - purchasePrice);
printf("Your change is: $%d\n", amountOfChange);
numberOfTwenties = amountOfChange / 20;
//amountOfChange = numberOfTwenties %= amountOfChange;
numberOfTens = (amountOfChange / 10);
numberOfFives = (amountOfChange / 5);
numberOfOnes = (amountOfChange / 1);
numberOfQuarters = (amountOfChange * 0.25);
// print change calculations here
printf("---------------------------------------------\n");
//display denominations of change here
printf("Twenties: %d\n", numberOfTwenties);
printf("Tens: %d\n", numberOfTens);
printf("Fives: %d\n", numberOfFives);
printf("Ones: %d\n", numberOfOnes);
printf("Quarters: %d\n", numberOfQuarters);
printf("Dimes: %d\n", numberOfDimes);
printf("Nickels: %d\n", numberOfNickels);
printf("Pennies: %d\n", numberOfPennies);
printf("---------------------------------------------\n");
printf("Thank you for using the Change Counter!");
getchar();
return EXIT_SUCCESS;
}
The problem is that my program doesn't work, it shows the change after the prompt but not the breakdown of denominations, I am sposed to use the "%" to bring down the change amount, but i havent found any examples. I don't know what else to say... besides I'm new and this post will help a lot of people...
Your program has undefined behaviour : you must use %Lf as the printf modifier to print a long double (same issue with your usage of scanf)

Cash Register Program - C

Good day! In a program I am writing for school we must make a cash register type program, seems simple enough, but for the life of me I can not get it to work. After taking in the number of products bought, then the price of all, the program must ask for the cash to pay, then give back the change. BUT the change must be given in amount of loonies back (or $1 bills), and then just the remaining cents. Help? I've gotten the loonies to work (somewhat) but I don't know how to do the change back.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int itemNum, justChange;
double prodPrice, tax, cashGiven, change, purchasePrice, changeGiven, changeBack, cashBack;
float totalPrice;
//Num of items
printf ("Number of items: ");
scanf("%d", &itemNum);
//Price of items
printf("Please enter price of items: ");
scanf("%lf", &prodPrice);
//Math Stuff
purchasePrice = itemNum*prodPrice;
tax = purchasePrice * 0.13;
totalPrice = purchasePrice*1.13;
//find change alone
//justChange = totalPrice
//Price Output
printf("Purchase price is: %.2lf \n",purchasePrice );
printf("TAX (HST 13%): %.2lf\n",tax );
printf("Total price is: %.2lf \n",totalPrice );
printf("Please Enter Cash: ");
scanf("%lf", &cashGiven);
printf("Please Enter Change: ");
scanf("%lf", &changeGiven);
//MAth stuuff again
double endCash;
double loony;
int yoloswag;
endCash = cashGiven - totalPrice;
loony = endCash/1;
loony = loony--;
if (loony<0)
printf ("Loonies: 0");
else
printf("Loonies: %.0lf \n",loony );
printf("change: %d ", totalPrice-floor(totalPrice) );
return 0;
}
Create an array with possible change values;
double cashValues[6] = {1, 0.5, 0.2, 0.1, 0.05, 0.01};
Then create a for loop in which you try to subtract the possible change values from the difference until the difference is zero.
double difference;
difference = cashGiven - totalPrice;
while (difference != 0) {
for(int i=0; i<6; i++) {
if(cashValues[i] <= difference) {
difference -= cashValues[i];
printf("%f \n", cashValues[i]);
i=0;
}
}
}

Resources