Semaphores not waiting on each other - c++

The problem I'm having is that the semaphores are not waiting on each other before the portion of the code is running. The output looks like:
Customer 1 arriving at lane 1 at 0 sec
Customer 1 in now number 1 at lane 1
Checkout1 now serving customer 1 for 10 sec
Customer 2 arriving at lane 2 at 3
Customer 2 in now number 1 at lane 2
Checkout2 now serving customer 2 for 15sec
Customer 3 arriving at lane 1 at 7 sec
Customer 3 in now number 2 at lane 1
Checkout1 now serving customer 3 for 8 sec
Customer 4 arriving at lane 2 at 9
Customer 4 in now number 2 at lane 2
Checkout2 now serving customer 4 for 75sec
Cusomter 1 has left checkout1
Customer 5 arriving at lane 1 at 12 sec
Customer 5 in now number 2 at lane 1
Checkout1 now serving customer 5 for 20 sec
Cusomter 3 has left checkout1
Cusomter 2has left checkout2
Cusomter 5 has left checkout1
Cusomter 4has left checkout2
The problem is that when the checkout1 is processing customer1, the customer is supposed to leave before another person is processed, however, the checkout1 then services another customer which is customer 3. Then near the end of the program, the people start actually leaving the checkouts. I'm pretty sure this is a problem with my semaphores.
Here is a dumbed down version of my code:
sem_t *mem_mutexCheckout1Count;
sem_t *mem_mutexCheckout2Count;
sem_t *mem_mutexCheckout1Line;
sem_t *mem_mutexCheckout2Line;
int *pmemCheckout1Line;
int *pmemCheckout2Line;
int main()
{
for(int i = 0; i < myCustomers.size(); i++)
{
totalArrivalTime += myCustomers[i].arrival;
if((pid = fork()) == 0)
{
InLine(myCustomers[i].serial, totalArrivalTime, myCustomers[i].processing);
_exit(0);
}
}
}
void InLine(int serial, int arrivalTime, int time_interval)
{
sleep(arrivalTime);
if(*pmemCheckout1Line <= *pmemCheckout2Line)
{
cout << "Customer " << serial << " arriving at lane 1 at " << arrivalTime << " sec" << endl;
sem_wait(mem_mutexCheckout1Line);
*pmemCheckout1Line += 1;
sem_post(mem_mutexCheckout1Line);
cout << "Customer " << serial << " in now number " << *pmemCheckout1Line << " at lane 1" << endl;
sem_wait(mem_mutexCheckout1Count);
cout << "Checkout1 now serving customer " << serial << " for " << time_interval << " sec" << endl;
sleep(time_interval);
*pmemCheckout1Line -= 1;
cout << "Cusomter " << serial << " has left checkout1" << endl;
sem_post(mem_mutexCheckout1Count);
}
else
{
cout << "Customer " << serial << " arriving at lane 2 at " << arrivalTime << endl;
sem_wait(mem_mutexCheckout2Line);
*pmemCheckout2Line += 1;
sem_post(mem_mutexCheckout2Line);
cout << "Customer " << serial << " in now number " << *pmemCheckout2Line << " at lane 2" << endl;
sem_wait(mem_mutexCheckout2Count);
cout << "Checkout2 now serving customer " << serial << " for " << time_interval << "sec" << endl;
sleep(time_interval);
*pmemCheckout2Line -= 1;
cout << "Cusomter " << serial << "has left checkout2" << endl;
sem_post(mem_mutexCheckout2Count);
}
}
My myCustomers vector looks like
Vectorindex-Customerserial-timeElapsedSincePrevCustomer-ProcessTime
-------------
[0] 1 0 10
[1] 2 3 15
[2] 3 4 8
[3] 4 2 75
[4] 5 3 20

If you want to prevent any other customer to be processed before the customer who is being processed on the moment leaves, only use one semaphore, which is locked when a customer is being processed and unlocked when the customer is leaving
if(*pmemCheckout1Line <= *pmemCheckout2Line)
{
cout << "Customer " << serial << " arriving at lane 1 at " << arrivalTime << " sec" << endl;
sem_wait(mem_mutexCheckout1Line);
*pmemCheckout1Line += 1;
cout << "Customer " << serial << " in now number " << *pmemCheckout1Line << " at lane 1" << endl;
cout << "Checkout1 now serving customer " << serial << " for " << time_interval << " sec" << endl;
sleep(time_interval);
*pmemCheckout1Line -= 1;
cout << "Cusomter " << serial << " has left checkout1" << endl;
sem_post(mem_mutexCheckout1Line);
}

I found out my semaphores were not in shared memory, hence the semaphores not working properly. I did:
mem_mutexCheckout1Count = (sem_t*) mmap(NULL, sizeof(mem_mutexCheckout1Count), PROT_READ | PROT_WRITE, MAP_SHARED|MAP_ANONYMOUS, -1, 0);
To all my mutex's to fix.

Related

Looping through a text file and outputting different data In C++

My code asks me to convert:
2 6 2 // # of quizzes (2), homeworks(6), exams(2)
Solution Key 10 10 10 10 20 20 20 20 100 100
Washington George 10 10 10 10 20 20 20 20 100 100
Jefferson Thomas 10 0 8 6 20 15 13 0 80 90
Franklin Benjamin 0 0 0 0 20 10 20 10 100 50
Lincoln Abraham 10 5 10 5 0 0 0 0 80 30
Madisonville James 5 7 9 3 10 12 14 16 0 0
Wilson Woodrow 2 4 6 8 10 12 14 16 74 89
Hoover Herbert 0 10 10 10 0 20 20 20 0 100
Roosevelt Franklin 0 0 0 0 0 0 0 0 0 0
Into this (in an output file):
# Last First Quiz HW Exam Total Average
- ---------- ----- ---- --- ---- ----- -------
Solution Key 20 100 200 320 100.00
- ---------- ----- ---- --- ---- ----- -------
1 Washington Georg 20 100 200 320 100.00
2 Jefferson Thoma 10 62 170 242 75.62
3 Franklin Benja 0 60 150 210 65.62
4 Lincoln Abrah 15 15 110 140 43.75
5 Madisonvil James 12 64 0 76 23.75
6 Wilson Woodr 6 66 163 235 73.44
7 Hoover Herbe 10 80 100 190 59.38
8 Roosevelt Frank 0 0 0 0 0.00
- ---------- ----- ---- --- ---- ----- -------
Class Average = 55.20
I have been using count controlled loops to obtain the quiz, homeworks, and exam scores, however my output looks like this:
# Last First Quiz HW Exam Total Average
- ---------- ----- ---- --- ---- ----- -------
- ---------- ----- ---- --- ---- ----- -------
- ---------- ----- ---- --- ---- ----- -------
Class Average = 1458176112
Here is my code:
#include <fstream>
#include <iostream>
#include <iomanip>
#include <cstring>
#include <climits>
#include <typeinfo>
using namespace std;
//Sample solution
//- /home/work/cpe211/Executables/Project_06/Project_06_solution
//Comparison script
//- /home/work/cpe211data/Project_06/CompareSolution.bash Project_06.cpp
int main(int argc, char* argv[])
{
if (argc != 3) // if the amount of arguments is greater than 2, perform this.
{
cout << endl;
cout << "Incorrect number of command line arguments provided. \n";
cout << "This program requires 2 command line arguments: \n";
cout << "An input filename and an output filename \n \n";
cout << "Program usage is: \n";
cout << "./Project_06 InputFileName OutputFileName \n \n";
return 1;
}
// Variable Delcaration
ifstream inFile; // input
ofstream outFile; // output
string inputFileName, outFileName;
string line1, line2, line3, first, last;
int quiznum, homenum, examnum, quiz, homework, exam, total, average, total_sol, count_quiz, count_exam, count_homework, count, homework_total, exam_total, quiz_total, average_p2, average_total;
// ***** Opening and naming command line argument ***** //
inputFileName = argv[1]; // assign command line argument value to a string variable
inFile.open(inputFileName.c_str());
cout << "Opening Input File: " << inputFileName << endl;
outFile.open(argv[2]);
cout << "Opening Output File: " << argv[2] << endl;
// ***** Testing to see if the file exists ***** //
while (inFile.fail()) // if the file does not exist, then do this.
{
cout << endl;
cout << string(15,'*') << " File Open Error " << string(15,'*') << endl;
cout << "==> Input file failed to open properly!!\n";
cout << "==> Attempted to open file: " << inputFileName << endl;
cout << "==> Please try again...\n";
cout << string(47,'*') << endl << endl;
inFile.clear(); // clears the input file stream
cout << "Enter the name of the input file: ";
cin >> inputFileName; // user inputs new name of file
inFile.open(inputFileName.c_str()); // opens the new input file
cout << inputFileName << endl; // echo prints the new input file name
cout << "Opening Output File: " << argv[2] << endl; // echo the output fule
}
// ***** Testing for output file existance ***** //
while (outFile.fail()) // if the file does not exist, then do this.
{
cout << endl;
cout << string(15,'*') << " File Open Error " << string(15,'*') << endl;
cout << "==> Output file failed to open properly!!\n";
cout << "==> Attempted to open file: " << argv[2] << endl;
cout << "==> Please try again...\n";
cout << string(47,'*') << endl << endl;
outFile.clear();
cout << "Enter the name of the output file: ";
cin >> outFileName; // recieves input for the new output file name
outFile.open(outFileName.c_str()); // opens the output file
cout << outFileName << endl; // echo prints new output file name
}
// ***** First line information ***** //
getline(inFile,line1,'\n'); // gets line 1
inFile >> quiz >> homework >> exam; // retrieves number of quiz, homework, and exam scores from the first line.
if (inFile.eof())
{
cout << endl;
cout << "*************" << " Input File Is Empty " << "*************" << endl;
cout << "==> The input file is empty.\n";
cout << "==> Terminating the program.\n";
cout << string(47,'*') << endl << endl;
outFile << "Input file " << inputFileName << " is empty. \n";
return 1;
}
// ***** Count initializers ****** //
count = 0;
count_quiz = 0;
count_homework = 0;
count_exam = 0;
// ***** Starting for output ***** //
outFile << " # " << "Last " << "First " << "Quiz " << " HW " << "Exam " << "Total " << "Average" << endl; // First line info for each part of the file
outFile << setw(3) << "-" << setw(12) << "----------" << setw(7) << "-----" << setw(6) << "----" << setw(6) << "---" << setw(6) << "----" << setw(7) << "-----" << setw(9) << "-------" << endl; // seperating dashes
// ***** Sample solution data ***** //
getline(inFile,line2,'\n');
while (inFile >> last >> first)
{
while (count_quiz < quiz)
{
inFile >> quiz; // gets the quiz scores
quiz_total = quiz + quiz; // total of all quiz scores
count_quiz++;
}
while (count_homework < homework)
{
inFile >> homework;
homework_total = homework + homework;
count_homework++;
}
while (count_exam < exam)
{
inFile >> exam; // gets exam scores
exam_total = exam + exam; // totals all exam scores found
count_exam++; // updates count
}
total_sol = quiz_total + homework_total + exam_total; // total score for solution set
average = (total_sol / total_sol) * 100; // average for solution set (100%)
outFile << last << first << quiz_total << homework_total << exam_total << total_sol << average << endl; // output of all the above info
}
outFile << setw(3) << "-" << setw(12) << "----------" << setw(7) << "-----" << setw(6) << "----" << setw(6) << "---" << setw(6) << "----" << setw(7) << "-----" << setw(9) << "-------" << endl; // seperating dashes
// ********* The following grabs the info from each line using count controlled loops ********* //
getline(inFile,line3,'\n'); // gets the new lines
while (inFile >> last >> first)
{
while (count_quiz < quiz) // while the count is less than the number of the quizzes, do this.
{
getline(inFile,line3,'\n'); // gets line 3 and updates each time
inFile >> quiz; // quiz scores
quiz_total = quiz + quiz; // total of all the quiz scores
outFile << quiz_total; // output for total quiz scores
count_quiz++; // updates count
}
while (count_homework < homework) // while the count is less than the number of specified homeworks, do this
{
getline(inFile,line3,'\n'); // gets line 3 and updates each time
inFile >> homework; // homework scores
homework_total = homework + homework; // total of all homework scores
outFile << homework_total; // output for total homework scores
count_homework++; // updates count
}
while (count_exam < exam) // while the count is less than than the number of specified exams, do this.
{
getline(inFile,line3,'\n'); // gets line 3 and updates each time
inFile >> exam; // exam scores
exam_total = exam + exam; // total of all exam scores
outFile << exam_total; // output for total exam scores
count_exam++; // updates count
}
outFile << last << first << quiz_total << homework_total << exam_total << endl;
total = quiz_total + homework_total + exam_total; // total # of quiz, homeworks, and exam scores added
average_p2 = total / average; // average for each student
average_total = (average_p2 + average_p2) / count; // total average for all students
}
outFile << setw(3) << "-" << setw(12) << "----------" << setw(7) << "-----" << setw(6) << "----" << setw(6) << "---" << setw(6) << "----" << setw(7) << "-----" << setw(9) << "-------" << endl << endl; // seperating dashes
outFile << "Class Average = " << average_total << endl; // outputs the total average of the exam.
outFile.close();
return 0;
}
TLDR: How do I loop through a text file and get its info, use them in calculations, and output it correctly?

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.

Exits while loop before condition is false?

This is a pretty specific question but my program seems to exiting its while loop before the condition is false. I added in quite a few memory checks for safety when I was debugging and it prints to screen that counter is 4 and SqRoot is 6 at the end which means it should still be looping through (TestNum=32). I definitely know it's getting past the loop with counter<=SqRoot because it prints both "The integer 32 is composite" and "The integer 32 is prime". Any help is very appreciated! Thanks so much
EDIT: I changed the overall logic of program and it is working now. Thanks!
#include <iostream>
#include <cmath>
using namespace std;
//Declare variables.
int TestNum, DivInt, SqRoot, PrintCounter(0), oppcounter;
float DivFloat, counter(2);
int main()
{
//Prompt user for input.
cout << "Input an positive integer to test its primality.";
cin >> TestNum;
//Check if input is positive.
while (TestNum < 0)
{
cout << "Please input a *positive* integer.";
cin >> TestNum;
}
//Square root.
SqRoot = sqrt(TestNum)+1;
//Loop to test if prime.
while (counter<=SqRoot)
{
++counter;
DivFloat = TestNum/counter;
DivInt = TestNum/counter;
oppcounter = TestNum/counter;
if (DivFloat-DivInt == 0)
{
++PrintCounter;
if (PrintCounter==1)
{
cout << "The integer " << TestNum << " is composite.\n " \
<< TestNum << " is divisible by\n";
};
cout << counter << " " << oppcounter;
cout << "counter* " << counter;
cout << " TestNum " << TestNum;
cout << " DivInt " << DivInt;
cout << " SqRoot " << SqRoot;
cout << " DivFloat " << DivFloat;
}
}
if (counter<=SqRoot)
{
cout << "The integer " << TestNum << " is prime.\n";
}
cout << "counter " << counter;
cout << " TestNum " << TestNum;
cout << " DivInt " << DivInt;
cout << " SqRoot " << SqRoot;
cout << " DivFloat " << DivFloat;
//End main.
return (0);
}
I am seeing the opposite behavior of what you are describing, and I can see why. It's possible that the code you have posted is different than the code you are executing.
As an aside, I added the line
cout << endl;
after the line
cout << " DivFloat " << DivFloat;
at couple of places to make the output more readable.
When I enter 32, I see the following output:
The integer 32 is composite.
32 is divisible by
4 8
counter* 4 TestNum 32 DivInt 8 SqRoot 6 DivFloat 8
counter 7 TestNum 32 DivInt 4 SqRoot 6 DivFloat 4.57143
When I enter 17, I see the following output:
counter 6 TestNum 17 DivInt 2 SqRoot 5 DivFloat 2.83333
The reasons for that:
You don't break out of the while loop when you have detected that a number is a composite.
As a result of that, you always break out of the while loop only when counter<=SqRoot evaluates to false. As a result, in the code below,
if (counter<=SqRoot)
{
cout << "The integer " << TestNum << " is prime.\n";
}
you never execute the line in the if block.
The program should behave correctly if you break out of the while loop when you detect a composite and change the logic in the last if block to:
if (counter > SqRoot)
{
cout << "The integer " << TestNum << " is prime.\n";
}
Why so strange check for prime?
for(int i = 2; i*i <= n; ++i)
{
if (n % i == 0)
{
cout << "not prime";
break;
}
}

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

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!

Varied interest rate calculator

Hey I am new to coding and was wondering if you guys could help me out with calculating different interest rates and then adding them to the next interest rate. So basically I'm trying to get interest rate A and adding it to the starting value of 100. then I want to get interest rate B for 100 and add that value to interest A. So far here is my code but I get 10 lines for each interest rate. Sorry if this sounds confusing but hopefully the code makes it more clear or maybe I could try to explain better if whoever reads this wants to. Thanks!!
int intv;
cout << " Accumulate interest on a savings account. ";
cout << " Starting value is $100 and interest rate is 1.25% ";
cout << endl;
intv = 100;
index = 1;
while ( index <= 10 )
{
cout << " Year " << index << " adds 1.25% for a total of " << .0125 * intv + intv << "." << endl;
cout << " Year " << index << " adds 1.27% for a total of " << .0127 * intv + intv << "." << endl;
cout << " Year " << index << " adds 1.28% for a total of " << .0128 * intv + intv << "." << endl;
cout << " Year " << index << " adds 1.30% for a total of " << .0130 * intv + intv << "." << endl;
cout << " Year " << index << " adds 1.31% for a total of " << .0131 * intv + intv << "." << endl;
cout << " Year " << index << " adds 1.32% for a total of " << .0132 * intv + intv << "." << endl;
cout << " Year " << index << " adds 1.35% for a total of " << .0135 * intv + intv << "." << endl;
cout << " Year " << index << " adds 1.36% for a total of " << .0136 * intv + intv << "." << endl;
cout << " Year " << index << " adds 1.38% for a total of " << .0138 * intv + intv << "." << endl;
cout << " Year " << index << " adds 1.40% for a total of " << .0140 * intv + intv << "." << endl;
index = index + 1;
}
Instead of doing this for me I just want hints. I wanna fix this myself but am stuck as to what I have to do.
The desired out come of this is for the program to give me this:
Year 1 adds 1.25 for a total of 101.25
year 2 adds 1.27 for a total of 102.52
year 3 adds 1.28 for a total of 103.80
year 4 adds 1.30 for a total of 105.09
year 5 adds 1.31 for a total of 106.41
year 6 adds 1.33 for a total of 107.74
year 7 adds 1.35 for a total of 109.09
year 8 adds 1.36 for a total of 110.45
year 9 adds 1.38 for a total of 111.83
year 10 adds 1.40 for a total of 113.23
Total interest credited was 13.23
Sounds like you could use a for loop:
double rate = 0.125;
for (unsigned int index = 0; index < max_rates; ++index)
{
cout << " Year " << index << " adds "
<< (rate * 100.0)
<< "% for a total of "
<< rate * intv + intv << "." << endl;
rate += 0.002;
}
You need use a function to replace
cout << " Year " << index << " adds 1.25% for a total of " << .0125 * intv + intv << "." << endl;
The function can convert the index to adds value like
double foo(int index);
The input value is 'index', the output value is adds value like 1.25%, 1.38% .etc.
Then delete all cout lines. And just add this line:
cout << " Year " << index << " adds " << foo(index) * 100.0 << "% for a total of " << foo(index) * intv + intv << "." << endl;
I guess that is you want.