C++: Trouble with ending a loop based on a condition? - c++

This code is used to run a loop three times, that takes the numbers of eggs gathered and outputs the number in dozens and extra until the user enters a negative number. Then, it prints out the average amount of eggs gathered (entered), and outputs the total number of dozens and extra.
The inputs we were assigned to use are:
43,
31,
-1,
24,
8,
14,
-999,
-5.
Everything is fine up until we input -5. Our teacher doesn't want the average or total number of dozens and extras to print (you'll see what I mean in the output).
The source code is as follows:
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int eggNum;
int eggDozens;
int eggExtra;
int eggTotal;
int loopCount;
int forCount;
float eggAvg;
int totalDozens;
int totalExtra;
for(forCount = 1; forCount <= 3; forCount=forCount + 1)
{
cout << left << "TEST #" << forCount << ":" << endl;
cout << "Welcome to Aunt Ellen\'s eggs to dozens converter!";
cout << endl << endl;
cout << "\tEnter the number of eggs gathered: ";
cin >> eggNum;
eggTotal = 0;
loopCount = 0;
while(eggNum >= 0)
{
eggDozens = eggNum / 12;
eggExtra = eggNum % 12;
if(eggDozens != 0)
{
if(eggExtra != 0)
{
cout << "\tYou have " << eggDozens << " dozen ";
cout << eggExtra << " eggs.";
cout << endl << endl;
}
else
{
cout << "\tYou have " << eggDozens << " dozen eggs.";
cout << endl << endl;
}
}
else
{
cout << "\tYou have " << eggExtra << " eggs.";
cout << endl << endl;
}
loopCount = loopCount + 1;
eggTotal = eggTotal + eggNum;
cout << "\tEnter the number of eggs gathered: ";
cin >> eggNum;
}
cout << endl << "TOTALS:" << endl;
eggAvg = eggTotal / float(loopCount);
cout << "\tOn average " << eggAvg << " eggs have been";
cout << " gathered.";
totalDozens = eggTotal / 12;
totalExtra = eggTotal % 12;
cout << endl << "\tA total of " << totalDozens << " dozen ";
cout << totalExtra << " and eggs have been gathered!" << endl;
cout << endl << endl;
}
return 0;
}
And the output:
TEST #1:
Welcome to Aunt Ellen's eggs to dozens converter!
Enter the number of eggs gathered: 43
You have 3 dozen 7 eggs.
Enter the number of eggs gathered: 31
You have 2 dozen 7 eggs.
Enter the number of eggs gathered: -1
TOTALS:
On average 37 eggs have been gathered.
A total of 6 dozen 2 and eggs have been gathered!
TEST #2:
Welcome to Aunt Ellen's eggs to dozens converter!
Enter the number of eggs gathered: 24
You have 2 dozen eggs.
Enter the number of eggs gathered: 8
You have 8 eggs.
Enter the number of eggs gathered: 14
You have 1 dozen 2 eggs.
Enter the number of eggs gathered: -999
TOTALS:
On average 15.3333 eggs have been gathered.
A total of 3 dozen 10 and eggs have been gathered!
TEST #3:
Welcome to Aunt Ellen's eggs to dozens converter!
Enter the number of eggs gathered: -5
TOTALS:
On average -1.#IND eggs have been gathered.
A total of 0 dozen 0 and eggs have been gathered!
I don't want the very last "TOTALS" and the lines following. I want the program to terminate after entering -5.

The simplest thing is to do this before entering the while loop:
cin >> eggNum;
if (eggNum < 0)
break ;
That will quit the for loop, and return 0;
You may, if you want to, add some comments to the caller about entering negative numbers before calling break.

You mentioned that you only want to omit the last block of TOTALS.
You can simply add a special case to leave the outer loop early in this case.
Right before this block, but after the closing brace of the while loop.
cout << endl << "TOTALS:" << endl;
eggAvg = eggTotal / float(loopCount);
Insert this:
if (forCount == 3) break;
If you just want to avoid printing whenever the average is less than 0, then instead you should insert in the same location.
if (eggAvg < 0) continue;
This will skip the rest of that iteration of the for loop.

I think a simple answer to your problem would be to just put an if statement around the printing total code. Like this:
if(eggNum > -5){ //won't print for negative 5
cout << endl << "TOTALS:" << endl;
eggAvg = eggTotal / float(loopCount);
cout << "\tOn average " << eggAvg << " eggs have been";
cout << " gathered.";
totalDozens = eggTotal / 12;
totalExtra = eggTotal % 12;
cout << endl << "\tA total of " << totalDozens << " dozen ";
cout << totalExtra << " and eggs have been gathered!" << endl;
cout << endl << endl;
}
I hope this helps!

Related

how to divide money in to different amounts

I'm trying to do this program for many hours, but I couldn't.
The question is I've to take some amount of money from user. Then I've to ask how many 5s he have and how many 2s he have. I've to convert that amount of money to 5s and 2s and 1s. User have unlimited source of 1s. In short if user enters 27 I've to tell him 5 5s and 1 2s.
Now i did this type of program in which I converted time(from seconds to years and so on)
Now I did this in program:-
int money;
cout << "How much amount of money= ";
cin >> money;
cout << endl;
int ao5;
cout << "how many number of 5 coins available in your drawer= ";
cin >> ao5;
cout << endl;
int ao2;
cout << "how many number of 2 coins available in your drawer= ";
cin >> ao2;
cout << endl;
int fchange, tchange, ochange;
ochange = (money / 1) % ao5%ao2;
tchange = (money / ao2) % ao5;
fchange = money / ao5;
cout << " " << fchange;
cout << " " << tchange;
cout << " " << ochange;
I've tried other methods. I tried dividing money by 5 and then subtract it with 5s I've but it makes no sense.
Can anyone just take me to right path?
You can use this
void divid(int num){
if(num>=5){
int remainderAfterdevidingTo5 = num%5;
int numOf5s = num/5;
std::cout << " numOf5s "<< numOf5s<< std::endl;
divid(remainderAfterdevidingTo5);
}else if(num>=2){
int remainderAfterdevidingTo2 = num%2;
int numOf2s = num/2;
std::cout << " numOf2s "<< numOf2s<< std::endl;
divid(remainderAfterdevidingTo2);
}else if(num>=1){
std::cout << " numOf1s " <<num<< std::endl;
}
}

How to write a function that checks combinations of 3 numbers?

I'm currently making a 2 player dice game and i need to create a function that checks the value of the dice combination you rolled. Ex: I rolled 3-4-2, I need the function to check if there is a payout for 3-4-2, example rolls and their payouts + code below
//Rolling 1-1-1 would give you 5x your wager
//Rolling 3 of the same number (except 1-1-1) would give you 2x wager
//Rolling 3 different numbers (ex 1-4-6) would give you 1x your wager
//Rolling 1-2-3 makes the player automatically lose a round and pay opposing Player 2x wager
#include <iostream>
#include <string>
#include <time.h>
using namespace std;
void roll_3_dice(int &dice1, int &dice2, int &dice3)
{
srand(time(NULL));
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
dice3 = rand() % 6 + 1;
return;
}
int main()
{
int cash = 90000;
int wager;
int r;
//dealer's die
int dealer1;
int dealer2;
int dealer3;
// your die
int mdice1;
int mdice2;
int mdice3;
while ( cash > 100 || round < 10 )
{
cout << "Set your wager: "<< endl;
cin >> wager;
while (wager < 100 || wager > 90000)
{
cout << "Minimum wager is 100; Maximum wager is 90000 ";
cin >> wager;
}
cout << "You wagered: " << wager << endl;
cout << "You have " << cash - wager << " remaining" << endl;
cash = cash - wager;
cout << endl;
cout << "Dealer will now roll the dice" << endl;
roll_3_dice(dealer1, dealer2, dealer3);
cout << "Dealer rolled the following: " << endl;
cout << dealer1 << "-" << dealer2 << "-" << dealer3 << endl;
cout << "It's your turn to roll the dice." << endl;
cout << endl;
cout << "Press any key to roll the dice" << endl;
cin >> r;
roll_3_dice(mdice1, mdice2, mdice3);
cout << "You rolled the following: " << endl;
cout << mdice1 << "-" << mdice2 << "-" << mdice3 << endl;
system ("pause`enter code here`");
}
}
I would suggest to write your algorithm on a paper first, like you did in the comments on top of the code.
Then, ask yourself what you need to process the final wager ? As in parameters. For instance, in your case, you may need a function which takes the initial wager, and the values of the three dices as entry parameters.
This function would return the final wager.
Finally, in the function itself, organize the algorithm by priority rules.
If 1-1-1 gives you 5x your wager, then it's a particular case which can be isolated at the top of the function maybe, and you can return 5 x initial wager directly, without any need to process further operations.
You'll just have to organize the different cases with if statements, regarding the priorities of each statement.
The 1-1-1 case has to come before the "same number for each dice" for example.
Hope this helps.

Problems finding out total sum using data structures and arrays

I have this code that has several funtions and am almost done, I just am having trouble finding the rental cost on my program.
My program reads a text file of cars and the rental cost as shown here:
2014 Toyota Tacoma 115.12 1
2012 Honda CRV 85.10 0
2015 Ford Fusion 90.89 0
2013 GMC Yukon 110.43 0
2009 Dodge Neon 45.25 1
2011 Toyota Rav4 65.02 1
2012 Mazda CX5 86.75 1
2016 Subaru Outback 71.27 0
2015 Ford F150 200.83 1
2010 Toyota Corolla 50.36 1
The float character is the price ( rental cost )
However I want the user to input the car number ( 1-10) choose how many days and output the rental cost. I am just having trouble how it would read the input of the car the user wants. This is my main code, but what I need is to tell if case 3 needs work.
#include <iostream>
#include <fstream>
using namespace std;
struct car {
int year;
char make[10];
char model[10];
float price;
int available;
} ;
void menu();
// Main Function
int main ()
{
// declare variables
int carAmount = 10;
int choice;
car carLib[carAmount];
char filename[10];
ifstream carInData;
float mostExpensive = 0;
int MostExpensiveIndex;
int count = 0;
int days;
int rentalCost = 0;
bool menu1 = false;
//prompt user for input file
cout << " Enter file name: ";
cin >> filename;
// Start loop menu
while(menu1 = true){
menu();
carInData.open(filename);
cin >> choice;
if (carInData.is_open()) {
// read list of names into array
for (; count < carAmount; count++) {
carInData >> carLib[count].year >> carLib[count].make >> carLib[count].model >> carLib[count].price >> carLib[count].available;
}
}
switch (choice) {
// Case 1 closes menu
case 1:
return 0;
break;
// Case 2 displays if car is available if 1, unavailable if 0
case 2:
// itterate through car array
for(count = 0; count < carAmount; count++){
// Displays if car is available or not
if (carLib[count].available == 1)
cout << " Available ";
else
cout << " Unavailable ";
// Display Cars
cout << carLib[count].year << " " << carLib[count].make << " " << carLib[count].model << " " << carLib[count].price << " " << "\n";
}
break;
// Display only available cars
case 3:
// itterate through car array
for(count = 0; count < carAmount; count++){
// Displays only available cars
if (carLib[count].available == 1){
cout << " Available ";
// Display Cars
cout << carLib[count].year << " " << carLib[count].make << " " << carLib[count].model << " " << carLib[count].price << " " << "\n";
}
}
break;
// Calculates rental cost
case 4:
cout << " Enter car number and how many days " << "\n";
cout << " Days: ";
cin >> days;
cout << "\n" << "Car: ";
cin >> carLib[count].price;
rentalCost += days*count;
cout << " Rental Cost for " << days << " days is " << rentalCost << "\n";
break;
// Finds most expensive car
case 5:
MostExpensiveIndex = count;
for (size_t carIndex = 0; carIndex < carAmount; ++carIndex) {
if (carLib[carIndex].price <= mostExpensive) continue;
mostExpensive = carLib[carIndex].price;
MostExpensiveIndex = carIndex;
}
const car & carI = carLib[MostExpensiveIndex];
cout << " Most Expensive car is: " << " " << carI.year << " " << carI.make << " " << carI.model << " " << carI.price << "\n";
break;
}
}
return 0;
}
void menu()
{
cout << " 1 - Exit program.\n";
cout << " 2 - Show Cars\n";
cout << " 3 - Show only available cars.\n";
cout << " 4 - Rental Cost\n";
cout << " 5 - Most Expensive Car\n";
}
Unless I'm misunderstanding something with how your code is suppose to work, I think case 3 works fine. HOWEVER, it's case 4 that you should be worried about
case 4:
cout << " Enter car number and how many days " << "\n";
cout << " Days: ";
cin >> days;
cout << "\n" << "Car: ";
cin >> carLib[count].price; // WHY IS THE USER CHANGING THE PRICE?
rentalCost += days*count; // WHY IS THE PRICE "DAYS * (CAR ID #)"
cout << " Rental Cost for " << days << " days is " << rentalCost << "\n";
break;
You can see my comments there. I would change this to
case 4:
cout << " Enter car number and how many days " << "\n";
cout << " Days: ";
cin >> days;
cout << "\n" << "Car: ";
cin >> count ;
// Note the decrement of 'count' by one, since you expect the user
// to enter a number 1-10
// Should probably include a check that the 'count' is valid
rentalCost += days*carLib[count-1].price;
cout << " Rental Cost for " << days << " days is " << rentalCost << "\n";
break;
Note that carLib increments from 0->9, but your user might think it counts from 1-10. It might help when you print option 2 (all car information) that you include the car ID number that you're expecting from the user.
Also a few more questions for you
You're storing the rental cost as an int (not sure if that's by design), so just remember that the days*price computation will get rounded.
The rentalCost is incrementing to be bigger and bigger, so I'm guessing the user is renting multiple cars?
You should maybe do a check as to whether the user can actually rent a car before increasing their rental cost.

After running a mathematical function, how do I not display it to the screen?

I apologize in advance for the terrible title, it's hard to find a few words that encapsulate my issue effectively.
I have to do a programming project for making a cash register. After I find the total amount of money for the items, I have to input a change value, and make change with twenties, tens, fives, singles, quarters, dimes, nickels, and pennies. I have done the programming to calculate the change in bills and coins, but my professor wants us to not include the bills or coins if there aren't any being returned.
Here is my code so far for it-
void find_change(){
double change_given, updated_price, coin_price;
//item_price_total = 318.32; keep this in here for testing purposes
//change_given = 405.23; ' '
int twenties,
tens,
fives,
singles,
quarters,
dimes,
nickels,
pennies;
//finds the change in bills
do{
cout << "How much change is given? " << endl;
while(!(cin >> change_given)){ //tests to make sure value entered can be used
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "Invalid input. Try again: ";
}
if(change_given < item_price_total){
cout << "You did not give the machine enough money" << endl;
}
}while(change_given < item_price_total);
updated_price =change_given-item_price_total;
cout << "The total price is: " << item_price_total << endl;
cout << "The change given is: " << change_given << endl;
cout << "The change back will be: " << updated_price << endl;
twenties = updated_price / 20;
cout << "Twenties: " << twenties << endl;
updated_price = updated_price -(twenties *20);
tens = updated_price/10;
cout << "Tens: " << tens << endl;
updated_price = updated_price - (tens*10);
fives = updated_price/5;
cout << "Fives: " << fives << endl;
updated_price = updated_price - (fives*5);
singles = updated_price/1;
cout << "Singles: " << singles << endl;
updated_price = updated_price - (singles*1);
//this part finds the coins left
coin_price = updated_price * 100;
//finds the change in coins
quarters = coin_price/25;
cout << "Quarters: " << quarters << endl;
coin_price = coin_price - (quarters*25);
dimes = coin_price/10;
cout << "Dimes: " << dimes << endl;
coin_price = coin_price - (dimes*10);
nickels = coin_price/5;
cout << "Nickels: " << nickels << endl;
coin_price = coin_price - (nickels*5);
pennies = coin_price/1;
cout << "Pennies: " << pennies << endl;
coin_price = coin_price - (pennies*1);
}
I apologize for the bad formatting of it when I pasted it all in here. The function runs fine by itself, by when the change given back doesn't include a certain bill or coin I don't know how to not include it. Thanks!
Add tests for the coins/notes values.
#include <iostream>
#include <vector>
using namespace std;
struct Currency {
const char * name;
int value;
};
Currency values[] = {
{"Twenty", 2000},
{"Tens", 10000},
{"Dimes", 10},
{"Pennies",1}
};
int main() {
int change = 101;
for(auto& i: values){
int units = change /i.value;
if(units)// test that there is some change with these coins/notes
std::cout << i.name << units << endl;
change -= units*i.value;
}
return 0;
}

Maybe a syntax issue here?

Homework problem I am helping one of my mentees out with (check my history, I have previously asked help with Java in more advanced programs. This is something simple I can't help her figure out). We need to use a while loop to read in numbers, keep track of the count, and keep summing up the numbers entered. We keep getting an error in line 24. Even when I comment it out and run it, the programs doesn't do what it is supposed to do. Been forever since I've done a program in C++ and I need the help of you guys!
#include <iostream>
using namespace std;
int main()
{
int num;
int sum = 0;
int count = 0;
float avg;
cout << "Enter numbers, 999 to quit" << endl;
cin >> num; //
while (num != 999)
{
cout << "Number entered is" << num << endl;
cout << "Enter numbers, 999 to quit" << endl;
cin >> num;
sum = sum + num;
count++;
}
cout << "Total numbers entered: " + count << endl;
cout << "Sum of numbers entered is " + sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" + avg << endl;
return 0;
}
cout << "Total numbers entered: " + count << endl;
cout << "Sum of numbers entered is " + sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" + avg << endl;
Change those +'s to <<'s.
cout << "Total numbers entered: " << count << endl;
cout << "Sum of numbers entered is " << sum << endl;
avg = sum/count;
cout << "Average of numbers entered:" << avg << endl;
#include<iostream>
using namespace std;
int main()
{
int num,count;
float sum,average;
cout << "Enter numbers, 999 to quit" << endl;
cin>>num;
count=0;
sum=0;
while (num!=999)
{
cout<<"Number entered is"<<num<<endl;
++count;
sum+=num;
cout << "Enter numbers, 999 to quit" << endl;
cin>>num;
}
if (count==0) {
count=1;
}// if the first number you enter is 999 count should be 1
// , otherwise avg will be (sum/0 ),which doesn't make sense.
cout << "Total numbers entered: " <<count << endl;
cout << "Sum of numbers entered is " <<sum << endl;
average = sum/count;
cout << "Average of numbers entered:"<<average << endl;
// use << not + because "Total..." is string type and count is int type
system("pause");
return 0;
}
You should pay attention to the type of variable when you do something,which often can cause small errors.