My assignment is utilizing loops. The program should accept input for the sales of 3 employees (Mary, Tom, and Chris). The flow should be as follows:
Initial? > number of sales to enter > enter sale amounts > display commission for sale at 17% > adds commission and sales to the respective variables >> continue until 'z' is input for inputSalesPerson >> display information
So I am trying to figure out why my return value for the tempComm variable isn't returning the correct value. If i was to enter 't' for variable inputSalesPerson it puts me into the switch case 't' no problem. Input number of sales and that works. But when I get to entering the salesAmount and then displaying commission it will not calculate correctly.
Also if I enter 'z' or 'Z' as the inputSalesPerson it will not end the program. I have a lot to go on this.
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int salesT = 0, salesC = 0, salesM = 0;
double amountT = 0, amountC = 0, amountM = 0;
double commT = 0, commC = 0, commM = 0;
double commRate = (17/100);
int num_sales;
double salesAmount, totalSales, tempComm;
char inputSalesPerson;
do
{
cout << "Enter the sales person's initial (\"Z\" to quit): ";
cin >> inputSalesPerson;
while(inputSalesPerson != 't' && inputSalesPerson != 'T' && inputSalesPerson != 'm' && inputSalesPerson != 'M' && inputSalesPerson != 'c' && inputSalesPerson != 'C' && inputSalesPerson != 'z' && inputSalesPerson != 'Z')
{
cin.get();
system("cls");
cout << "Invalid input for employee. Please Input (T)om, (C)hris, (M)ary, or (Z) to End : ";
cin >> inputSalesPerson;
}
switch(inputSalesPerson)
{
case 't' :
case 'T' :
system("cls");
cout << "Enter the number of sales : ";
cin >> num_sales;
while(num_sales < 1 || num_sales > 5)
{
system("cls");
cout << "Invalid number of sales. Please enter a value between 1 and 5 : ";
cin >> num_sales;
}
salesT += num_sales;
for(int i = 0; i<num_sales; i++)
{
cin.get();
system("cls");
cout << "Enter the sale amount : ";
cin >> salesAmount;
while(salesAmount < 0)
{
cin.get();
system("cls");
cout << "Invalid sale amount. Please enter a positive amount : ";
cin >> salesAmount;
}
tempComm = salesAmount + (salesAmount * commRate);
cout << fixed << setprecision(2) << "Commission earned by tom on this sale is : " << tempComm << endl;
cin.get();
amountT += salesAmount + tempComm;
commT += tempComm;
totalSales += amountT;
}
break;
}
}while(inputSalesPerson != 'z' || 'Z');
return 0;
}
****EDIT****
Thank you for the information on single-step debugging. Thanks to that comment I was able to learn about using the debugging tool more in depth and that helped me get everything working a bit better.
I've commented your code at the areas that need fixing. Also, there's a problem with using cin.get() all over the place. I assume that you do this to discard the return character after each input. But if the standard input (cin) is empty when you call cin.get() it will block the program until something is input. This is what happens when you enter more than one num_sales:
for (int i = 0; i<num_sales; i++)
{
cin.get();
It handles the first fine, but on the second loop you get:
Enter the sale amount : 20
Commission earned by tom on this sale is : 23.40
// cin.get() blocks here, with no user instructions to enter the next sale amount
I've commented out all the cin.get(). It will still work the same because the cin operator >> discards whitespaces and newlines, so even if there is a \n newline character still in the buffer, the next time you do something like cin >> num_sales it will discard the newline anyway.
#include <iomanip>
#include <iostream>
using namespace std;
int main()
{
int salesT = 0, salesC = 0, salesM = 0;
double amountT = 0, amountC = 0, amountM = 0;
double commT = 0, commC = 0, commM = 0;
double commRate = (17 / 100.0); // Int divided by int will round to an int.
// commRate is 0.0. Divide by double instead (17 / 100.0)
int num_sales;
double salesAmount, totalSales = 0, tempComm; // totalSales needs to be initialised to
// zero, otherwise it holds a garbage value.
char inputSalesPerson;
do
{
cout << "Enter the sales person's initial (\"Z\" to quit): ";
cin >> inputSalesPerson;
while (inputSalesPerson != 't' && inputSalesPerson != 'T' && inputSalesPerson != 'm' && inputSalesPerson != 'M' && inputSalesPerson != 'c' && inputSalesPerson != 'C' && inputSalesPerson != 'z' && inputSalesPerson != 'Z')
{
//cin.get();
system("cls");
cout << "Invalid input for employee. Please Input (T)om, (C)hris, (M)ary, or (Z) to End : ";
cin >> inputSalesPerson;
}
switch (inputSalesPerson)
{
case 't':
case 'T':
system("cls");
cout << "Enter the number of sales : ";
cin >> num_sales;
while (num_sales < 1 || num_sales > 5)
{
system("cls");
cout << "Invalid number of sales. Please enter a value between 1 and 5 : ";
cin >> num_sales;
}
salesT += num_sales;
for (int i = 0; i<num_sales; i++)
{
//cin.get();
//system("cls");
cout << "Enter the amount for sale number " << i+1 << ": ";
cin >> salesAmount;
system("cls"); // I would put the clear here,
// Otherwise the user can't see the commission made by Tom
while (salesAmount < 0)
{
//cin.get();
system("cls");
cout << "Invalid sale amount. Please enter a positive amount : ";
cin >> salesAmount;
}
tempComm = salesAmount + (salesAmount * commRate);
cout << fixed << setprecision(2) << "Commission earned by tom on this sale is : " << tempComm << endl;
//cin.get();
amountT += salesAmount + tempComm;
commT += tempComm;
totalSales += amountT; // I think you mean to add salesAmount maybe?
}
break;
}
} //while (inputSalesPerson != 'z' || 'Z');
// Even if { this ^^^^} is false, ^^^ this is always
// 'Z' char will convert to bool, any non-zero value is true.
while (inputSalesPerson != 'z' && inputSalesPerson != 'Z');
return 0;
}
Related
I am writing a program, the program is basically a guessing game. Computer displays a number and the user has to guess whether their number is higher, lower or correct. I have already made the program and its all dandy, but the only not dandy part is that I cannot figure out how to get rid of the input buffer when the user decides to play the game again. Every time the user wants to play the game, the game starts again but with the same input as the last game. I have tried putting cin.clear() in any spot I could think and also cin.clear(). But it just seems to not work. How do I clear the input?
#include <iostream>
using namespace std;
int main ()
{
int num1 = 100;
char choice;
num1 = num1 / 2;
do
{
cout << "My guess is " << num1 << ". " << "Enter 'l' if your number is lower, 'h' if it is higher, 'c' if it is correct: ";
cin >> choice;
cin.clear();
if (choice == 'h')
{
num1 = num1 + 100;
num1 = num1 / 2;
}
if (choice == 'l')
{
num1 = num1 + num1;
num1 = num1 - 11;
num1 = num1 / 2;
}
if (choice == 'c')
{
cout << "Great! Do you want to play again (y/n)?: ";
cin >> choice;
}
} while (choice != 'c' || choice == 'Y' || choice == 'y' || choice == 'n' || choice == 'N');
return 0;
}
In order to restart the game, you need to reset num1. Put the inital value in a variable that you don't change.
const int init = 100;
char choice;
int num1 = init / 2;
When the computer has guessed correctly:
if (choice == 'c')
{
num1 = init / 2; // reset
cout << "Great! Do you want to play again (y/n)?: ";
cin >> choice;
}
You could also leave the loop condition at:
} while(choice != 'N' && choice != 'n');
You should also work on the divide and conquer algorithm. For the computer to be effective, it should always make a guess in the middle of the range that is still possible, and that's not what it's doing right now. It jumps up and down, even outside the established range. An alternative could be to keep two variables to be able to shrink the possible range effectively. You could also do two separate loops, one inner loop for guessing the number and one outer that only asks the user if he/she wants to play again.
Example:
#include <iostream>
int main() {
const int initlo = 1;
const int inithi = 100;
char choice;
do {
std::cout << "Think of a number [" << initlo << "," << inithi << "]\n";
int numlo = initlo; // initialize the range
int numhi = inithi;
int guess;
do {
guess = (numlo + numhi) / 2; // guess in the middle of the range
std::cout
<< "My guess is " << guess << ". "
<< "Enter 'l' if your number is lower, 'h' if it is higher, 'c' "
"if it is correct: ";
std::cin >> choice;
if(choice == 'h') // must be in the range (guess,numhi]
numlo = guess + 1;
else if(choice == 'l') // must be in the range [numlo,guess)
numhi = guess - 1;
// exit the loop if the user cheats or the answer is correct
} while(numlo <= numhi && choice != 'c');
if(choice == 'c') std::cout << "Great! ";
else std::cout << "Cheater! ";
std::cout << "Do you want to play again (y/n)?: ";
std::cin >> choice;
} while(choice == 'Y' || choice == 'y');
std::cout << "Bye\n";
}
Hello this is my first program with a do-while loop and its taken me a little while to get it down. I need to have the user enter 2 numbers, and raise the first number to the second number. I have finally got the coding to ask if "they would like to raise another number by a power?" and when they say yes and enter 2 new numbers the total adds the total from the first 2 numbers entered with the second set of numbers and so on. Can someone help me out with this problem? Here is the coding and a picture to help y'all out!
#include <iostream>
using namespace std;
int main()
{
int num;
int pow;
int p;
int power = 1;
char yesno = 'y' || 'Y';
do
{
cout << "Enter a number: ";
cin >> num; "\n";
cout << "Enter the power to raise: ";
cin >> pow; "\n";
for (p = 1; p <= pow; p++)
{
power = power * num;
}
cout << "The total is: " << power << endl;
cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while (yesno != true);
}
The problem of the ever-increasing answer is that power is not being reset inside the do-while loop, so the last value is being carried forward into the next loop. You need reset it at the top of the loop.
Another problem with the code is that the exit condition would never occur.
Try this instead:
int main()
{
int num;
int pow;
int p;
int power;
char yesno;
do
{
power = 1; // <<<<<< reset power here
cout << "Enter a number: ";
cin >> num; "\n";
cout << "Enter the power to raise: ";
cin >> pow; "\n";
for (p = 1; p <= pow; p++)
{
power = power * num;
}
cout << "The total is: " << power << endl;
cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while (yesno == 'y' || yesno == 'Y'); // <<<<< test for 'yes' response
}
When you reach line } while (yesno != true); and loop back to do {, the variable power still holds the previous num^pow. You will need to assign power = 1 after do {.
#include <iostream>
// you also need
#include <cmath> // for pow()
using namespace std;
int main()
{
// int num; Declare variables where they're used. As locally as possible.
// int pow;
// int p;
// int power = 1;
// char yesno = 'y' || 'Y'; I don't know what you were trying to do here
// the expression 'y' || 'Y' will always be true
// and evaluate to some value different from null
// wich will be assigne to yesno. But with no con-
char yesno; // sequences since it later gets overwritten by
do // cin >> yesno; There is no need to initialize
{ // this variable.
cout << "Enter a number: ";
int num;
cin >> num; "\n"; // the statement "\n"; has no effect.
cout << "Enter the power to raise: ";
int pow;
cin >> pow; "\n"; // again. no effect.
// for (p = 1; p <= pow; p++) as user4581301 has pointed out in the
// comments it is more ... natural in C
// to loop from 0 to < max:
int power = 1; // now its time to declare and define power ;)
for(int p = 0; p < pow; ++p) // notice that you can declare variables
{ // in the init-statement of a for-loop
// power = power * num; shorter:
power *= num;
}
cout << "The total is: " << power << /* endl; + 2 x '\n' gives: */ << "\n\n\n";
// cout << "\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
// } while (yesno != true); that condition will most likely always be true
// since the user would have a hard time to input
// a '\0' character, which would evaluate to false
// better:
} while(yesno == 'y' || yesno == 'Y' );
}
done.
Without clutter:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
char yesno;
do {
cout << "Enter a number: ";
int num;
cin >> num;
cout << "Enter the power to raise: ";
int pow;
cin >> pow;
int power = 1;
for(int p = 0; p < pow; ++p)
power *= num;
cout << "The total is: " << power << "\n\n\n";
cout << "Would you like to raise another number by a power? [Y/N]";
cin >> yesno;
} while(yesno == 'y' || yesno == 'Y' );
}
I'm having trouble writing a while loop for this code that has the gender as the Loop Control Variable (when you input the gender, it's in a do-while loop with specific conditions for it to be valid). also, i don't know what to do to be able to calculate the number and percent of candidates accepted.
char gender; //INPUT Gender of candidate
char genderOk; //CALC & OUT Checks validity of gender input
int height; //INPUT Height of candidate
int heightOk; //CALC & OUT Valid height range for candidate
int weight; //INPUT Weight of candidate
int weightOk; //CALC & OUT Valid weight range for candidates
int count; //INPUT Counter of the FOR loop
int candidates; //INPUT Amount of candidates per test
int acceptCand; //CALC & OUT # of candidates accepted per test
int acceptPerc; //CALC & OUT % of candidates accepted per test
// INPUT - describe input here
cout << left;
for(count = 1; count <= 3; count++)
{
cout << "TEST RUN #" << count << endl << endl << endl;
cout << "Please enter candidate's information (enter 'X' to "
"exit).\n";
gender = 'f';
while(gender != 'X' || gender != 'x')
{
do
{
cout << "Gender: ";
cin.get(gender);
cin.ignore(1000, '\n');
genderOk = gender != 'm' && gender != 'M' && gender != 'f'
&& gender != 'F';
if(genderOk)
{
cout << "***** Invalid gender; please enter M or F "
"*****";
cout << endl;
}
}while(genderOk);
do
{
cout << "Height: ";
cin >> (height);
cin.ignore(1000, '\n');
heightOk = height >= 24 && height <= 110;
if(!heightOk)
{
cout << "***** Invalid height; please enter a height "
"in inches between 24 and 110. *****";
cout << endl;
}
}while(!heightOk);
do
{
cout << "Weight: ";
cin >> weight;
cin.ignore(1000, '\n');
weightOk = weight >= 50 && weight <= 1400;
if(!weightOk)
{
cout << "***** Invalid weight; please enter a weight "
"in lbs between 50 and 1400. *****";
cout << endl;
}
}while(!weightOk);
if(gender == 'm' || gender == 'M')
{
heightOk = height >= 65 && height <= 80;
weightOk = weight >= 130 && weight <= 250;
if(heightOk && weightOk)
{
cout << RESULT << "ACCEPTED!\n\n\n\n";
}
else
{
if(!heightOk)
{
if(!weightOk)
{
cout << RESULT << "rejected based on the "
"HEIGHT and WEIGHT "
"requirements."
"\n\n\n\n";
}
else
{
cout << RESULT << "rejected based on the "
"HEIGHT requirement."
"\n\n\n\n";
}
}
else
{
if(!weightOk)
{
cout << RESULT << "rejected based on the "
"WEIGHT requirement."
"\n\n\n\n";
}
}
}
}
if(gender == 'f' || gender == 'F')
{
heightOk = height >= 62 && height <=75;
weightOk = weight >= 110 && weight <= 185;
if(heightOk && weightOk)
{
cout << RESULT << "ACCEPTED!\n\n\n\n";
}
else
{
if(!heightOk)
{
if(!weightOk)
{
cout << RESULT << "rejected based on the "
"HEIGHT and WEIGHT "
"requirements.\n\n\n\n";
}
else
{
cout << RESULT << "rejected based on the"
" HEIGHT requirement."
"\n\n\n\n";
}
}
else
{
if(!weightOk)
{
cout << RESULT << "rejected based on the "
"WEIGHT requirement."
"\n\n\n\n";
}
}
}
}
}
}
The while loop condition
To solve your problem with having the while loop condition, instead of checking what the input gender is in your main loop (this is actually never validated since the gender is assigned INSIDE the while loop), your control condition for your while loop can be a Boolean variable.
This:
bool isQuit = false;
while(!isQuit)
{
...
Instead of:
gender = 'f';
while(gender != 'X' || gender != 'x')
{
...
Then when the user can input a gender, you check for your quitting condition. (In this case, where gender == 'X' || gender == 'x'.)
if(gender == 'X' || gender == 'x') {
isQuit = true;
break;
} else if(genderOk) {
cout << "***** Invalid gender; please enter M or F "
"*****";
cout << endl;
}
...
This will now break out of the do..while loop that is used to enter in the gender. All that needs to be added is a check to see if the user has chosen to quit the input loop or not.
// After the do..while loop for inputting gender
if(isQuit) {
break;
}
Now the program will break out of the main while loop that we defined as having a loop condition of while(!isQuit).
Note: The above will not break out of the for loop that runs three 'test runs'. To use the isQuit variable to quit out of the entire program, add the following code at the end of the for loop:
if(isQuit) {
break;
}
} // END OF YOUR FOR LOOP
Calculating candidates
To calculate the number of candidates, the number of accepted candidates and the percentage of accepted candidates, we need to keep track of two things.
Total number of candidates (Store value in candidates)
Total accepted candidates (Store value in acceptCand)
First we need to setup our variables correctly:
int candidates; //INPUT Amount of candidates per test
int acceptCand; //CALC & OUT # of candidates accepted per test
float acceptPerc; //CALC & OUT % of candidates accepted per test
candidates = 0;
acceptCand = 0;
acceptPerc = 0;
Whenever we reach a point where the user in not entering values, we assume that they have entered a valid candidate. Where you check what gender the candidate is, we can increase the candidate counter by 1.
if(gender == 'm' || gender == 'M') {
candidates++;
...
if(gender == 'f' || gender == 'F') {
candidates++;
...
Now that we are keeping track of the total number of candidates, we now need to know the number of ACCEPTED candidates. To do this, we increase the acceptCand variable by one each time a candidate is accepted.
if(heightOk && weightOk) {
cout << "ACCEPTED!\n\n\n\n";
acceptCand++;
}
And finally, to get the percentage of accepted candidates, you would do the following:
acceptPerc = (acceptCand / (float)candidates) * 100;
Note: acceptPerc is a float datatype so that we can use decimal places. We type cast the candidates variable to float so that we avoid integer division which would cause us to lose the decimal places and return only whole numbers.
I keep getting errors when I try to execute the following program, and I do not know if something is wrong with one of my functions or what(the way I wrote it). I know something is wrong with line 129 in my code, but whenever I try to make changes other syntax errors show up. Basically there is something wrong with my syntax and since I'm learning debugging I'm having a hard time with this.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
//declare global functions
void num_units( int& input1 );
void student_fees( float& num1, int& var1 );
void state_resident( bool& cond1 );
char parking_decal( char& ans1 );
void other_student_services_fees( char& ans2, char& ans3 );
int main ()
{
bool not_a_resident = false;
char want_as_sticker = 'x', want_parking_decal = 'y', want_id_card = 'z';
string semester_session = "not enrolled yet";
int units = 0, semester = 0;
float price_per_unit = 0, unit_fees = 0, student_services_fee = 0, parking_decal_fee = 0, total_fees = 0, as_sticker_fee = 19.50, id_card_fee = 13.00;
num_units( units );
student_fees( student_services_fee, semester );
state_resident( not_a_resident );
parking_decal( want_parking_decal );
other_student_services_fees( want_as_sticker, want_id_card );
//determine total student services fee depending on user's preferences
if ( want_as_sticker == 'n' )
student_services_fee = student_services_fee - as_sticker_fee;
if ( want_parking_decal == 'n' )
student_services_fee = student_services_fee - parking_decal_fee;
if ( want_id_card == 'n' )
student_services_fee = student_services_fee - id_card_fee;
//determine price per unit
if ( not_a_resident == false )
price_per_unit = 325.00;
else
price_per_unit = 46.00;
//determine unit_fees
unit_fees = price_per_unit * units;
//determine parking decal price
if ( ( parking_decal( want_parking_decal ) == 'y' ) && ( (semester == 1) || (semester == 3) ))
parking_decal_fee = 45.00;
else
parking_decal_fee = 85.00;
//calculate total fees
total_fees = unit_fees + student_services_fee;
if ( semester == 0 )
semester_session = "Fall";
else if ( semester == 1)
semester_session = "Winter";
else if ( semester == 2)
semester_session = "Spring";
else
semester_session = "Summer";
cout << "For " << semester_session + " " << "your total fees are $ " << total_fees;
return 0;
}
void num_units( int& input1 )
{
cout << "SMC Fee Calculator" << endl;
cout << "Enter number of units enrolled: ";
cin >> input1;
cout << endl;
}
//calculates the unit fees
void student_fees( float& num1, int& var1 )
{
do
{
//determines semester unit price
cout << "Is this Fall[0], Winter[1], Spring[2] or Summer[3] session: ";
cin >> var1;
if ( var1 == 0 || var1 == 2 )
num1 = 50.50;
else if ( semester == 1 || semester == 3 )
num1 = 48.50;
else
cout << endl;
cout << "I'm sorry. That's an improper selection. Please try again.\n";
}while ( var1 <= 4 && var1 >= 0 );
}
void state_resident( bool& cond1 )
{
cout << "Are you a state resident[0] or not[1]: ";
cin >> cond1;
cout << endl;
}
char parking_decal( char& ans1 )
{
do
{
cout << "Want a parking decal? [y/n]: ";
cin >> ans1;
if ( (ans1 != 'y') || (ans1 != 'n') )
cout << "I'm sorry. That's not a valid input. Please try again.\n";
else
break;
}while ( (ans1 != 'y') || (ans1 != 'n') );
cout << endl;
return ans1;
}
void other_studentservices_fees( char& ans2, char& ans3 )
{
//Ask if user wants an AS sticker.
do
{
cout << "Want an AS sticker? [y/n]: ";
cin >> ans2;
//proof answer
if ( (ans2 != 'y') || (ans2 != 'n') )
cout << "I'm sorry. That's not a valid input. Please try again.\n";
else
break;
}
cout << endl;
//Ask if user wants an AS sticker.
do
{
cout << endl << "Want an ID card? [y/n]: ";
cin >>ans3;
//proof answer
if ( (ans2 != 'y') || (ans2 != 'n') )
cout << "I'm sorry. That's not a valid input. Please try again.\n";
else
break;
}
cout << endl;
}
Output should look like this:
SMC Fee Calculator
Enter number of units enrolled: 18
Is this Fall[0], Winter[1], Spring[2] or Summer[3] session: 0
Are you a state resident[0] or not[1]: 0
Want a parking decal? [y/n]: n
Want an AS sticker? [y/n]: n
Want an ID card? [y/n]: n
For Fall semester, your total fees are $ 846.00
SMC Fee Calculator
Enter number of units enrolled: 6
Is this Fall[0], Winter[1], Spring[2] or Summer[3] session: 1
Are you a state resident[0] or not[1]: 1
Want a parking decal? [y/n]: y
Want an AS sticker? [y/n]: y
Want an ID card? [y/n]: y
For Winter semester, your total fees are $ 2043.50
I've looked at your program for 5 min and there are so many errors I'm not even sure where to begin...
Line 131 and 145: You forgot the do-while condition.
Line 141: Should probably replace "ans2" by "ans3" (shitty names for variables by the way)
Line 89: Semester is undeclared, seems like you were supposed to use "var1" instead, which is another horrible name.
Line 12: You declare the function "other_student_services_fees" yet you never define it
At that point I just gave up on you. We are not here to do your homework for you, those are basics errors you could have found yourself.
Greetings,
I'm just looking for a bit of help here. Here's the prompt:
For research purposes the admissions officers of your local university wants to know how well female and male students perform in certain courses. The user enters the number of courses to be considered. The student's data for each course is provided as a GPA followed by a letter code representing the gender of the student in this format: each line of input consists of a real number representing the student's GPA followed by the letter code f (for female students); m (for male students).
The number of entries (students) for each course is not known and the number 0.0 followed by the letter O indicates the end of data for specific course.
That being said, this is an introduction to c++ and as such; arrays, strings, and anything else outside of int, floats, doubles, and char is basically not allowed. In the code there needs to be the ability to type in various entries in any order (male entry followed by female and as well as the opposite.)
the issue i'm having is this, at the end of the program it is required to give an output of "General School Averages" which are sorted by female and male. I understand how to get the total in which to divide the problem, i just can't seem to get the sum. Anytime I try to get the sum, the value for the first course (first time through loop) is not kept so I can't figure out for the life of me how to do it. Any hints or assistance would be greatly appreciated. I know the code is long and kinda "brutish" so bear with me on that part. here's the code
//GPA calculator for Ghemri
//dealing with gpa range 0.0-4.0, set cap?
//try a do while loop
#include <iostream>
using namespace std;
int main(void)
{
int size, counter;
//int studentTotal= 0;
char gender;
double studentInfo,total,sum, avg;
double minRange = 0.0, maxRange = 4.0;
double maxGpa=0,gpaAvg,gpaSum;
double femaleSum, femaleAvg, femaleTotal;
double maleSum, maleAvg, maleTotal;
int femaleNumber,maleNumber, gpaNumber;
double sumFemaleAvg;// femaleGeneralAvg;//sumMaleAvg, maleGeneralAvg;
cout << "\nPlease enter the number of courses you want considered: ";
cin >> size;
while(size <=0)
{
cout << "\nInvalid entry, number of course must be greater than zero\n";
cin >> size;
}
//sumFemaleAvg+=femaleAvg;
for(int course =1; course <= size; course++)
{
maleTotal = 0;
femaleTotal=0;
total = 0;
femaleNumber = 0;
maleNumber = 0;
gpaNumber = 0;
maxGpa= 0;
gpaSum = 0;
//double doubleArray[course] = {femaleAvg};
cout << "\nEnter student information(0.0 O to end):\t";
cin >> studentInfo >> gender;
while(studentInfo < minRange || studentInfo > maxRange)
{
cout << "\nInvalid entry, try again...\n";
cout << "Enter student's information(0.0 O to end): \t";
cin >> studentInfo >> gender;
}
if(studentInfo > maxGpa)
{
maxGpa=studentInfo;
}
if(studentInfo > 3.00)
{
gpaSum=studentInfo;
gpaNumber=1;
}
if(gender == 'f' && studentInfo > minRange && studentInfo < maxRange)
{
femaleNumber=1;
femaleSum = studentInfo;
maleSum=0;
}
if(gender == 'm' && studentInfo > minRange && studentInfo < maxRange)
{
maleNumber=1;
maleSum = studentInfo;
femaleSum=0;
}
sum =studentInfo;
counter = 0;
counter++;
while(studentInfo != 0.0 && gender != 'O')
{
cout << "Enter student information(0.0 O to end):\t";
cin >> studentInfo >> gender;
if(studentInfo > maxGpa)
{
maxGpa=studentInfo;
}
if(studentInfo < minRange || studentInfo > maxRange)
{
cout << "\nInvalid entry, try again...\n";
cout << "Enter student's information(0.0 O to end): \t";
cin >> studentInfo >> gender;
}
if(gender != 'm' && gender !='f'&& gender != 'O')
{
cout << "Invalid entry, enter m for male or f for female\n";
cout << "Enter student's information(0.0 O to end): \t";
cin >> studentInfo >> gender;
}
sum +=studentInfo;
total+=counter;
avg = sum/total;
if(studentInfo > 3.00)
{
gpaSum+=studentInfo;
gpaNumber++;
gpaAvg= gpaSum/gpaNumber;
}
if(gender == 'f' || gender =='F')
{
femaleSum+=studentInfo;
femaleNumber++;
//femaleTotal+=femaleNumber;
femaleAvg = femaleSum/femaleNumber;
//sumFemaleAvg = femaleAvg;
}
if(gender == 'm' || gender == 'M')
{
maleSum+=studentInfo;
maleNumber++;
//maleTotal+=maleNumber;
maleAvg = maleSum/maleNumber;
}
if(studentInfo == 0 && gender == 'O')
{
cout << "\nResults for course "<< course<<":\n";
cout << "Female Student Average\t Male Student Average\n";
cout << "\t";
if(femaleNumber==0)
{
cout<< "N/A" << "\t\t\t";
}
else
{
cout<< femaleAvg <<"\t\t\t";//femaleAvg
}
if(maleNumber==0)
{
cout << "N/A\n";
}
else
{
cout<<maleAvg << endl;
//sumMaleAvg = maleAvg;
}
cout << "\nHighest GPA: " << maxGpa<<endl;
cout << "Highest average GPA for course "<< course << ": "<< gpaAvg<< endl;
}
}
sumFemaleAvg = femaleAvg;
}
/*double genAvg[]={femaleAvg};
result+=genAvg[course];*/
sumFemaleAvg+=femaleAvg;
cout<< "this is a test for the value sum " << sumFemaleAvg<<endl;
//cout<< "this is another test " << result <<endl;
//maleGeneralAvg = sumMaleAvg/course;
/*cout << "the sum is " << sumFemaleAvg<<endl;
cout << "the other sum is "<< sumFemaleAvg2<<endl;
cout << "the other other sum is " << femaleAvg;*/
return 0;
}
Try to avoid extreme repetition and factor common operations into functions. I'll "bear with you" for now, but really there's no reason I should. This is the first thing you need to learn as a programmer.
It looks like the variable sumFemaleAvg is supposed to be summed over loop iterations. However the line sumFemaleAvg = femaleAvg; overwrites the variable every time. Do
sumFemaleAvg += femaleAvg;
and likewise for other variables you wish to add up over multiple iterations.