I'm having trouble trying to do this assignment for my class for a couple of days now and would like some help.
The assignment is to write a program that informs the user of their acceptance status based on their heigh and weight qualifications depending on their gender.
At the end of the program it wants to output the number of candidates that were accepted and the average of those accepted to the overall number of candidates.
Assignment - https://www.saddleback.edu/faculty/slinker/CS1A/CS1A_Fall2013/Assignment8.pdf
We can't use switch, conditional operators, and selection (only for outputting the correct message to the results). We can only use loops and complex boolean expressions
The problems I'm having is:
If all 3 of my inputs are valid, why are they not outputting if they are accepted and if one of the input (height or weight) or both were rejected then why isn't it outputting it. Is my boolean variable incorrect? If so, how do I fix it.
Why am i unable to exit the loop/program when I enter X. Is my while loop correct or no?
Is there any selection statements I can change into "not selection-statements".
Here is my code
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char gender;
int height;
int weight;
bool heightOK;
bool weightOK;
int candidateCount;
int validCandidateCount;
bool invalidGender;
bool invalidHeight;
bool invalidWeight;
float percentOutput;
candidateCount = 0;
validCandidateCount = 0;
cout << "Please enter the candidate's information (enter 'X' to exit)."
<< endl;
do
{
cout << "Gender: ";
cin.get(gender);
cin.ignore (1000,'\n');
invalidGender = ( !(gender == 'm' ||
gender == 'M' ||
gender == 'f' ||
gender == 'F' ));
candidateCount = candidateCount + 1;
if(invalidGender)
{
cout << "***** Invalid gender; please enter M or F*****" << endl;
}
}while(invalidGender);
while (gender != 'X' || gender != 'x')
{
candidateCount = candidateCount + 1;
do
{
cout << "Height: ";
cin >> height;
invalidHeight = height < 24 || height > 110;
heightOK = ((gender == 'm' || gender == 'M') &&
(height > 65 && height < 80));
heightOK = heightOK || ((gender == 'f' || gender == 'F') &&
(height > 62 && height < 75));
if(invalidHeight)
{
cout << "***** Invalid height; please enter a height in inches between 24 and 110. *****"
<< endl;
}
}while(invalidHeight);
do
{
cout << "Weight: ";
cin >> weight;
invalidWeight = weight < 50 || weight > 1400;
weightOK = ((gender == 'm' || gender == 'M') &&
(weight > 130 && weight < 250));
weightOK = weightOK || ((gender == 'f' || gender == 'F') &&
(weight > 110 && weight < 185));
if(invalidWeight)
{
cout << "***** Invalid weight; please enter a weight in lbs between 50 and 1400."
<< endl;
}
}while(invalidWeight);
if(heightOK && weightOK)
{
cout << "This candidate has been ACCEPTED!" << endl;
validCandidateCount = validCandidateCount + 1;
}
else if (!heightOK)
{
cout << "This candidate has been rejected based on the HEIGHT requirement."
<< endl;
}
else if (!weightOK)
{
cout << "This candidate has been rejected based on the WEIGHT requirement."
<< endl;
}
else if (!(heightOK && weightOK))
{
cout << "This candidate has been rejected based on the HEIGHT and WEIGHT requirements"
<< endl;
}
do
{
cout << "Gender: ";
cin.get(gender);
cin.ignore (1000,'\n');
candidateCount = candidateCount + 1;
if(invalidGender)
{
cout << "***** Invalid gender; please enter M or F*****" << endl;
}
}while(invalidGender);
}
cout << validCandidateCount << " candidate(s) accepted!" << endl;
percentOutput = validCandidateCount / candidateCount;
cout << "That's " << percentOutput <<"%!" << endl;
return 0;
}
The main while loop should have and condition.
while(gender !='X' && gender!='x)
And your selection code has wrong conditional statements.
if(heightOK && weightOK)
{
cout << "This candidate has been ACCEPTED!" << endl;
validCandidateCount = validCandidateCount + 1;
}
else if (!heightOK) // you have written else if(heightOK)
{
cout << "This candidate has been rejected based on the HEIGHT requirement."
<< endl;
}
else if (!weightOK) // you have written else if(weightOK)
{
cout << "This candidate has been rejected based on the WEIGHT requirement."
<< endl;
}
else if (!(heightOK && weightOK))
{
cout << "This candidate has been rejected based on the HEIGHT and WEIGHT requirements"
<< endl;
}
You should remove that invalidgender condition in the last do while loop, otherwise it will cause an infinite loop even if you wish to exit by pressing X.
Instead the invalid gender condition can be placed at the starting of main While loop.
And invalidGender variable should be assigned its value again otherwise it will pick up the previously stored value.
invalidGender = ( !(gender == 'm' ||
gender == 'M' ||
gender == 'f' ||
gender == 'F' ));
the whole code
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
char gender;
int height;
int weight;
bool heightOK;
bool weightOK;
int candidateCount;
int validCandidateCount;
bool invalidGender;
bool invalidHeight;
bool invalidWeight;
double percentOutput;
candidateCount = 0;
validCandidateCount = 0;
cout << "Please enter the candidate's information (enter 'X' to exit)."
<< endl;
cout << "Gender: ";
cin.get(gender);
while (gender != 'X' && gender != 'x')
{
candidateCount = candidateCount + 1;
do
{
invalidGender = ( !(gender == 'm' ||
gender == 'M' ||
gender == 'f' ||
gender == 'F' ));
if(invalidGender)
{
cout << "***** Invalid gender; please enter M or F*****" << endl;
cout << "Gender: ";
cin>>gender;
cin.ignore (1000,'\n');
}
}while(invalidGender);
do
{
cout << "Height: ";
cin >> height;
invalidHeight = height < 24 || height > 110;
heightOK = ((gender == 'm' || gender == 'M') &&
(height > 65 && height < 80));
heightOK = heightOK || ((gender == 'f' || gender == 'F') &&
(height > 62 && height < 75));
if(invalidHeight)
{
cout << "***** Invalid height; please enter a height in inches between 24 and 110. *****"
<< endl;
}
}while(invalidHeight);
do
{
cout << "Weight: ";
cin >> weight;
invalidWeight = weight < 50 || weight > 1400;
weightOK = ((gender == 'm' || gender == 'M') &&
(weight > 130 && weight < 250));
weightOK = weightOK || ((gender == 'f' || gender == 'F') &&
(weight > 110 && weight < 185));
if(invalidWeight)
{
cout << "***** Invalid weight; please enter a weight in lbs between 50 and 1400."
<< endl;
}
}while(invalidWeight);
if(heightOK && weightOK)
{
cout << "This candidate has been ACCEPTED!" << endl;
validCandidateCount = validCandidateCount + 1;
}
else if (!heightOK)
{
cout << "This candidate has been rejected based on the HEIGHT requirement."
<< endl;
}
else if (!weightOK)
{
cout << "This candidate has been rejected based on the WEIGHT requirement."
<< endl;
}
else if (!(heightOK && weightOK))
{
cout << "This candidate has been rejected based on the HEIGHT and WEIGHT requirements"
<< endl;
}
cout << "Gender: ";
cin>>gender;
cin.ignore (1000,'\n');
}
cout << validCandidateCount << " candidate(s) accepted!" << endl;
percentOutput = (double)validCandidateCount / (double)candidateCount;
cout << "That's " << percentOutput*100 <<"%!" << endl;
return 0;
}
The Boolean data types need to be declared true or false. And this needs to be set before iterations.
Also:
The program needs to run before a user can input x to quit.
std:string QUIT;
QUIT = “XXX”;
Then use selection structure.
Related
So, to further explain my question, when I fill my whole board in tic tac toe with "X" and "O" and there is no winner, the game keeps on playing even when the spaces are filled. It just keeps saying enter a row and column still. It doesn't know when to stop. I'm not sure whats wrong with my code.
Problems where I think it is: I think my problem lies in my checkWinner function because my bool winner = false is suppose return my statement "Its a tie" if every space on my board is filled but it doesn't output that. It also may be my main function.
How do I fix this problem because I've been stuck trying to figure it out. So if anyone can help, I appreciate it. Thanks!
#include <iostream>
#include <string>
using namespace std;
const int ROWS = 3; // For the number of rows.
const int COLS = 3; // For the number of columns.
void showBoard(char[][COLS], int); // Shows the board.
void playerChoice(char[][COLS], char); // shows the player choice.
bool checkWinner(char[][COLS], string&); // check the winner.
char board[ROWS][COLS] = { { '*', '*', '*' }, { '*', '*', '*' }, { '*', '*', '*' } };
int main()
{
char board[ROWS][COLS] = { { '*', '*', '*' }, { '*', '*', '*' }, { '*', '*', '*' } }; // displays
whats inside the board.string gwinner = " "; // holds the winner until there is a winner.
bool winner;
int counter = 1;
showBoard(board, 3); // displays the board.
playerChoice(board, 'X');
showBoard(board, 3);
while (counter) {
playerChoice(board, 'O');
showBoard(board, 3);
if (winner = checkWinner(board, gwinner))
break;
playerChoice(board, 'X');
showBoard(board, 3);
if (winner = checkWinner(board, gwinner))
break;
}
cout << gwinner;
}
void showBoard(char arr[][COLS], int SIZE) // Displays the board.
{
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++)
cout << '|' << arr[row][col];
cout << '|' << endl;
}
}
void playerChoice(char arr[][COLS], char name) // what row and column the user wants.
{
int row, columns; // for the user to enter the row and column.
int occupied;
do {
cout << "What row would you like?\n";
cout << "Row: ";
cin >> row;
while (row < 1 || row > 3) // input validation.
{
cout << "Error please pick a row between 1 and 3.\n";
cout << "Row: ";
cin >> row;
cout << endl;
}
cout << "What column would you like?\n";
cout << "Column: ";
cin >> columns;
while (columns < 1 || columns > 3) // input validation.
{
cout << "Error,please pick a column between 1 and 3.\n";
cout << "Column: ";
cin >> columns;
cout << endl;
}
if (arr[row - 1][columns - 1] == '*') // checks to see if * is empty
{
arr[row - 1][columns - 1] = name; // diplays either X or O
occupied = 1;
}
else {
cout << "\nThis space is occupied.\n";
cout << "Please select again\n";
occupied = 0;
}
} while (occupied == 0);
}
bool checkWinner(char arr[][COLS], string& gwinner) // Check if the winner met the right conditions
{
bool winner = false;
if ((arr[0][0] == arr[0][1]) && (arr[0][1] == arr[0][2]) && (arr[0][1] != '*')) // checks row
{
winner = true;
cout << "The winner is:" << arr[0][0] << endl;
}
else if ((arr[1][0] == arr[1][1]) && (arr[1][1] == arr[1][2]) && (arr[1][1] != '*')) // checks row
{
winner = true;
cout << "The winner is:" << arr[1][0] << endl;
}
else if ((arr[2][0] == arr[2][1]) && (arr[2][1] == arr[2][2]) && (arr[2][1] != '*')) // checks row
{
winner = true;
cout << "The winner is:" << arr[2][0] << endl;
}
else if ((arr[0][0] == arr[1][0]) && (arr[1][0] == arr[2][0]) && (arr[1][0] != '*')) // checks columns
{
winner = true;
cout << "The winnner is:" << arr[0][0] << endl;
}
else if ((arr[0][1] == arr[1][1]) && (arr[1][1] == arr[2][1]) && (arr[1][1] != '*')) // checks
columns
{
winner = true;
cout << "The winnner is:" << arr[0][1] << endl;
}
else if ((arr[0][2] == arr[1][2]) && (arr[1][2] == arr[2][2]) && (arr[1][2] != '*')) // checks
columns
{
winner = true;
cout << "The winnner is:" << arr[0][2] << endl;
}
else if ((arr[0][0] == arr[1][1]) && (arr[1][1] == arr[2][2]) && (arr[1][1] != '*')) // checks
diagonal
{
winner = true;
cout << "The winnner is:" << arr[0][0] << endl;
}
else if ((arr[2][0] == arr[1][1]) && (arr[1][1] == arr[0][2]) && (arr[1][1] != '*')) // checks
diagonal
{
winner = true;
cout << "The winnner is:" << arr[2][0] << endl;
}
else {
gwinner = "It's a Tie."; // else if the winner is a tie.
winner = false;
}
return winner; // returns the winner
}
The code I have to write is basically a mini bank. It asks for an initial amount, the type of action, and a second operator for that action.
I'm not allowed to use else, but am allowed to use if statements (I don't understand why), nor am I allowed to use a loop or an array.
This is the code I have so far:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int operand1;
int operand2;
float output;
char action;
int main()
{
cout << fixed << showpoint << setprecision(2);
cout << "Enter the initial balance [1-1000]: " << endl;
cin >> operand1;
cout << "Enter an action (D, W, I or C):" << endl;
cin >> action;
cout << "Enter the second operand:" << endl;
cin >> operand2;
if ((action != 'D' && action != 'W' && action != 'I' && action != 'C') || (operand1 > 1000 || operand1 < 1) ||
(action == 'I' && operand2 > 15 || operand2 < 1) || (action == 'C' && operand2 != 20 && operand2 != 10 && operand2 != 5) ||
(operand2 > 1000 || operand2 < 1))
{
cout << "Input out of range" << endl;
return 0;
}
if (action == 'D')
{
output = (operand1 + operand2);
cout << "The new account balance is " << output << endl;
}
if (action == 'W')
{
output = (operand1 - operand2);
if (output<0)
{
cout << "Input out of range" << endl;
return 0;
}
cout << "The new account balance is " << output << endl;
}
if (action == 'I')
{
output = ((float)operand1 + (((float)operand2 / 100) * (float)operand1));
cout << "The new account balance is " << output << endl;
}
if (action == 'C')
{
output = operand1 % operand2;
cout << operand1 / operand2 << " bills dispensed plus " << output << endl;
}
cin.get();
cin.get();
return 0;
}
On certain instances, I get multiple errors instead of just one. For example:
Enter the initial balance [1-1000]: 1030
Enter an action (D, W, I or C): D
Enter the second operand: 40
Input out of range
However, it seems to just move on when it sees the error anyway, and I get this output:
Enter the initial balance [1-1000]:
1030
Input out of range
Enter an action (D, W, I or C):
D
Enter the second operand:
40
The new account balance is 1070.00
I can't seem to figure out how to have only one output, and for it to just display the error with no balance, without using an else statement.
Use switch (action):
https://en.cppreference.com/w/cpp/language/switch
After the cases it can have a default.
Also lots of conventions forbid else, but not forbid elseif - are you sure elseif is forbidden in your case?
But even if elseif is allowed - switch is better to read and is a more elegant solution.
You can use switch by taking all the commands as different cases. This is what others have already said.
My contribution would be that you could put your first if statement i.e. the error case under the default case.
And before using switch statements, could you check if it is ever explicitly stated that you can't use 'else if' statements. If not, you should use that. It is not the same as an 'else' statement.
&& has a higher precedence than ||
if (
(action != 'D' && action != 'W' && action != 'I' && action != 'C') ||
(operand1 > 1000 || operand1 < 1) ||
// (action == 'I' && operand2 > 15 || operand2 < 1) ||
(action == 'I' && (operand2 > 15 || operand2 < 1)) ||
(action == 'C' && operand2 != 20 && operand2 != 10 && operand2 != 5) ||
(operand2 > 1000 || operand2 < 1))
{
cout << "Input out of range" << endl;
return 0;
}
To have more traceability, on what the code does, it would be worth the effort to do:
if (action != 'D' && action != 'W' && action != 'I' && action != 'C')
{
cout << "Input out of range; action " << action << endl;
return 0;
}
if (operand1 > 1000 || operand1 < 1)
{
cout << "Input out of range; 1st operand: " << operand1 << endl;
return 0;
}
...
I am currently working on a program for a project, that asks for the user to enter the specific sport they want to play and their age for reservations at a recreation area. I am confused on how to store their sport and age into an array so that it can be displayed later in the program, if they select to view all reservations made by one or more users. If anyone could help me with figuring out how to store a single or multiple user input into an array so that it can be displayed later in the program that would be great!
#include <iostream>
#include <string>
using namespace std;
int main()
{
char t; // Type of sport selected
char g, G; // Gliding
char h, H; // Hang-gliding
char f, F; //Flying
int a; // Age of patron
double x; // Rates
int s; // Selection from menu
int i; // Arrays variable
int num;
char sport[100]; // Array for all sports of patrons
int age[100]; // Array for all ages of patrons
cout << "Please pick from the following menu" << endl;
cout << "1. Add a new reservation" << endl;
cout << "2. Print all reservations" << endl;
cout << "3. Print all reservations for a given sport" << endl;
cout << "4. Quit" << endl;
cin >> s;
for (i = 0; i < num; ++i)
if (s == 1) {
cout << "Please enter f/F for flying, g/G for gliding and h/H for hang-gliding" << endl;
cin >> t;
getline (cin, sport[i]);
cout << "Please enter the age of patron, minimum age is 16" << endl;
cin >> a;
if ((t == 'f' || t == 'F') && (a <= 25)) {
x = 68.95;
}
else if ((t == 'g' || t == 'G') && (a <= 25)) {
x = 73.95;
}
else if ((t == 'h' || t == 'H') && (a <= 25)) {
x = 99.95;
}
else if ((t == 'f' || t == 'F') && (a > 25)) {
x = 55.95;
}
else if ((t == 'g' || t == 'G') && (a > 25)) {
x = 65.95;
}
else if ((t == 'h' || t == 'H') && (a > 25)) {
x = 92.95;
}
cout << "The insurance rate is $ " << x << endl;
}
else if (s == 2) {
cout << "A patron aged " << a << " reserved a session of " << t << endl;
}
else if (s == 3) {
}
else if (s == 4);
return 0;
You should make a class Patron that contains the multiple informations, then make an array of type Patron instead of multiple arrays:
class Patron
{
//data for each patron...
};
in main:
Patron patrons[...];
You could also use dynamic containers, like vector instead of an array.
std::vector<Patron> patrons;
I am writing a "time travel" program which is supposed to ask the user for the current time, their target travel time, relay those values to be converted into minutes in a function and then based on if the time difference is too high it will not allow the time travel or if it is allowed it will print if they are in the future or the past. My issue right now is that the current time, which is only supposed to be relevant the first iteration, or the first "jump" of the program is not being updated after the jump occurs, and the program defaults to it instead of the target time, which is supposed to be the technical "current time" after the jump has occurred. I have been trying to figure this out for hours and I can't, so I am hoping someone could help me out.
Thank you for your time
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int compute_time_difference(int c_hrs, int c_mins, bool c_am, int t_hrs, int t_mins, bool t_am);
void print_future();
void print_past();
void print_SecurityProtocol();
int main()
{
int c_hrs, c_mins;
int t_hrs, t_mins;
int system_time2;
int time_difference2;
bool c_am = 0;
bool t_am = 0;
char c, c2, Y, N, y, n, jumpAgain;
string am_or_pm_current, am_or_pm_target;
bool g_stop = true;
cout << "Welcome to Po Sled" << endl;
cout << "\tSystem booting..." << endl;
for (int i = 0; i<1; i++) //for loop to run once
{
cout << "\n\tEnter current time below: " << endl;
cout << "\t>Enter hour: "; //User inputs current time in hours
cin >> c_hrs;
while (c_hrs > 12 || c_hrs < 1)
{
cout << "Error: Please enter an hour in the range [1, 12]: ";
cin >> c_hrs;
}
cout << "\t>Enter minutes: "; //User inputs current time in minutes
cin >> c_mins;
while (c_mins > 59 || c_mins < 0) {
cout << "Error: Please enter minutes in the range [0, 59]: ";
cin >> c_mins;
}
cout << "\t>Is it AM or PM?: "; //Classifying if current time is AM or PM
cin >> am_or_pm_current;
while (am_or_pm_current != "am" && am_or_pm_current != "AM" && am_or_pm_current != "pm" && am_or_pm_current != "PM") { //Checks if valid input, if not repeats message until valid
cout << "\tError: Please enter AM/am or PM/pm: ";
cin >> am_or_pm_current;
}
if ((am_or_pm_current == "am") || (am_or_pm_current == "AM"))
{
c_am = 1;
}
else if ((am_or_pm_current == "pm") || (am_or_pm_current == "PM"))
{
c_am = 0;
}
cout << "\n\tCurrent system time set to " << c_hrs << ":" << setw(2) << setfill('0') << c_mins << am_or_pm_current << endl;
cout << "\n\t\tIs this time correct (Y or N)? ";
cin >> c;
while (c != 'Y' && c != 'y' && c != 'n' && c != 'N')
{
cout << "\t\t\tError: Please enter Y/y or N/n: ";
cin >> c;
}
if (c == 'N' || c == 'n')
{
continue;
}
else
{
cout << "\n\tSystem initializing and TARDIS unit warming...." << endl;
cout << "\tThe Po Sled is engaged and ready for input." << endl;
}
}
do {
//Starts a loop for target jump
cout << "\n\tEnter target time below: " << endl; //Enters target time of jump
cout << "\t>Enter Hour: ";
cin >> t_hrs;
while (t_hrs > 12 || t_hrs < 1) {
cout << "Error: Please enter an hour in the range [1, 12]: ";
cin >> t_hrs;
}
cout << "\t>Enter minutes: ";
cin >> t_mins;
while (t_mins > 59 || t_mins < 0) {
cout << "\tError: Please enter minutes in the range [0, 59]: ";
cin >> t_mins;
}
cout << "\n\tIs it AM or PM?: ";
cin >> am_or_pm_target; //Classifying if target time is AM or PM
while (am_or_pm_current != "am" && am_or_pm_current != "AM" && am_or_pm_current != "pm" && am_or_pm_current != "PM")
{ //Validates input is AM or PM
cout << "\tError: Please enter AM/am or PM/pm: ";
cin >> am_or_pm_target;
}
if ((am_or_pm_target == "am") || (am_or_pm_target == "AM"))
{
t_am = 1;
}
else if ((am_or_pm_target == "pm") || (am_or_pm_target == "PM"))
{
t_am = 0;
}
cout << "\tTarget time set to " << t_hrs << ":" << setw(2) << setfill('0') << t_mins << am_or_pm_target; //Sets target time
cout << "\n\t\tIs this time correct (Y or N)? "; //Validates if target time entered is correct
cin >> c2;
while (c2 != 'Y' && c2 != 'y' && c2 != 'n' && c2 != 'N')
{
cout << "\t\t\tError: Please enter Y/y or N/n: ";
cin >> c2;
}
time_difference2 = compute_time_difference(c_hrs, c_mins, c_am, t_hrs, t_mins, t_am);
if (time_difference2 > 360) //If time difference is greater than 6 hours prints error function
{
print_SecurityProtocol();
continue;
}
if (c2 == 'N' || c2 == 'n')
{
continue;
}
cout << "\tJump was made, the current time is " << t_hrs << ":" << setw(2) << setfill('0') << t_mins << am_or_pm_target << endl;
if (time_difference2 < 0 && time_difference2 > -360) //If time difference is less than 0 prints past function
{
print_past();
}
else if (time_difference2 >= 0 && time_difference2 <= 360) //If time difference is ahead of current time prints future function
{
print_future();
}
cout << "\tWould you like to jump again (Y/N)? ";
cin >> jumpAgain;
while (jumpAgain != 'Y' && jumpAgain != 'y' && jumpAgain != 'n' && jumpAgain != 'N') //Input validation
{
cout << "\t\t\tError: Please enter Y/y or N/n: ";
cin >> jumpAgain;
}
if (jumpAgain == 'n' || jumpAgain == 'N') //User exiting program
{
if (time_difference2 < 0)
{
cout << "\t\tSystem shutting down; enjoy the past.\n" << endl;
}
else if (time_difference2 >= 0 && time_difference2 < 360)
{
cout << "\t\tSystem shutting down; enjoy the future.\n" << endl;
}
}
if (jumpAgain == 'Y' || jumpAgain == 'y')
{
continue;
}
} while (jumpAgain != 'n' && jumpAgain != 'N');
return 0;
}
int compute_time_difference(int c_hrs, int c_mins, bool c_am, int t_hrs, int t_mins, bool t_am) //Computes time differences.
{
int currentTime_hours, currentTime_minutes, targetTime_hours, targetTime_minutes, currentTime, targetTime;
int time_difference;
if (c_am == 1) //if c_am is true and it is morning
{
if (c_hrs == 12)
{
currentTime_hours = c_hrs * 0;
}
else if (c_hrs != 12)
{
currentTime_hours = (c_hrs * 60);
currentTime_minutes = c_mins;
currentTime = currentTime_hours + currentTime_minutes; //Sets the value of the current time
}
}
else if (c_am == 0) //if c_am is false and it is afternoon time
{
if (currentTime_hours == 12)
{
c_hrs = c_hrs * 60;
}
else if (currentTime_hours != 12)
{
currentTime_hours = ((c_hrs + 12) * 60);
currentTime_minutes = c_mins;
currentTime = currentTime_hours + currentTime_minutes; //Sets the value of the current time
}
}
if (t_am == 1) //if t_am is true and it is morning time
{
if (targetTime_hours == 12) //if target hours equal to 12 special math
{
targetTime_hours = t_hrs*0;
}
else if (targetTime_hours != 12) //else do this math
{
targetTime_hours = ((t_hrs) * 60);
targetTime_minutes = t_mins;
targetTime = targetTime_hours + targetTime_minutes;
}
}
else if (t_am == 0) //if target time equal to pm then do this math
{
if (targetTime_hours == 12)
{
targetTime_hours = t_hrs * 60;
}
else if (targetTime_hours != 12) //else if target time not equal to 12 then do normal pm math
{
targetTime_hours = ((t_hrs + 12) * 60);
targetTime_minutes = t_mins;
targetTime = targetTime_hours + targetTime_minutes;
}
}
time_difference = targetTime - currentTime;
cout << "the difference computed is " << time_difference;
return time_difference;
}
void print_SecurityProtocol() //Function which prints security protocol error message
{
cout << "\tSecurity Protocols Engaging" << endl;
cout << "\t\tError: The time difference is greater than 6 hours." << endl;
cout << "\t\t\tPlease re-enter target time." << endl;
}
void print_past() //Function that prints when a user is in the past
{
cout << "\tHold onto your lower posterior regions" << endl;
cout << "\n\t\tYou are now in the relative past" << endl;
}
void print_future() //Function that prints when a user is in the future
{
cout << "\tHold onto your lower posterior regions" << endl;
cout << "\n\t\tYou are now in the relative future " << endl;
}
Why do you not use a system time call, instead of getting user input for the 'current time'? Also, use a 24-hour clock instead of a 12-hour and you have removed the need to cater for am/pm within your process.
AM n ot much of a coder but c_hrs*60 would be (at least) 60 hours and (at most) 24*60 which, with the exception of a drive across Europe, Russia, Australia or the Northern US would be excessive time recording. Do you not mean to refer to MINUTES instead of hours (c_mins*60)?
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.