My question is how do I validate the data for getTestScore function? Need the program to tell the user invalid data, please enter a score in between 0 and 100 in the event that they put in a negative number or number over 100. Thanks.
#include <iostream>
using namespace std;
//function prototypes
float getTestScore();
float calcAverage(float score1, float score2, float score3);
int main()
{
float s1, s2, s3; //these variables are used to store test scores
float average;
//call getTestScore function to get the test scores
s1 = getTestScore();
s2 = getTestScore();
s3 = getTestScore();
//call calcAverage to calculate the average of three test scores
average = calcAverage(s1, s2, s3);
//display the average
cout << "average of three test scores(" << s1 << "," << s2 << "," << s3 << ")is" << average << endl;
return 0;
}
//function definitions/implementation getTestScore function gets a test score from the user and
//validates the score to make sure the value is between 0 and 100. if score is out of range
//getTestScore function allows the user to re-enter the score. This function returns a valid score
// to the caller function
float getTestScore()
{
float score = 0;
do
{
cout << "Enter test score: " << endl;
cin >> score;
} while (!(score >= 0 && score <= 100));
return score;
}
// calcAverage function calculates and returns the average of the three test scores passed to
//the function as input.
float calcAverage(float score1, float score2, float score3)
{
float average;
average = (score1 + score2 + score3) / 3;
return average;
}
You can change the while loop to this:
float getTestScore()
{
float score = 0;
while ((cout << "Enter test score: ")
&& (!(cin >> score) || score < 0 || score > 100)) {
// This part only gets executed on invalid input
cout << "invalid data, please enter a score in between 0 and 100 ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
return score;
}
By using a "Do-While" your executing the block of code at least once before checking the input.
The first input is therefore not checked by your condition:
while (!(score >= 0 && score <= 100));
Using a standard while loop and therefore checking this condition before hand should resolve your problem.
Related
This program takes the name of the course, grade and the number of units of a course to calculate the grade point average. I want the program to exit the while loop after the user enters the letter q and display the phrase outside the loop.
#include <iostream>
using namespace std;
int main()
{
char name[20];
float unit;
float score;
float avg = 0;
float total = 0;
int q=0, c=0;
while (name[20]!= q)
{
cout << "Enter a Name";
cin >> name;
cout << "Enter score";
cin >> score;
cout << "Enter unit of surce";
cin >> unit;
avg = avg + score * unit;
total = total + unit;
cout << "cantinue(c) or break(q)";
cin >> name[20];
}
avg = avg / total;
cout << "gpa :" << " " << avg;
return 0;
}
Problem:
You're comparing a char with an int variable called q. That won't break the loop when the user enters 'q', it will break the loop when the player enters the character that corresponds to the value that the q variable stores (in your case it is probably 0 in ASCII that is '\0').
Additionally, you're accessing a variable that is out of the bonds of the array which is Undefined Behaviour. You should write name[19] instead.
Solution:
Compare name[19] to 'q' instead.
while(name[19] != 'q')
...
std::cin >> name[19];
Additional information:
using namespace std; is considered a bad practice (More info here).
During the first check of the while condition your char variable is uninitializated, which will result in Undefined Behaviour. Solve this initialazing it to some value or using a do while loop instead;
I would recommend to create an additional char variable to store the character that controls the exit.
Full code:
#include <iostream>
int main()
{
char name[20];
float unit;
float score;
float avg = 0;
float total = 0;
char quit;
do
{
std::cout << "Enter a Name: ";
std::cin >> name;
std::cout << "Enter score: ";
std::cin >> score;
std::cout << "Enter unit of source: ";
std::cin >> unit;
avg = avg + score * unit;
total = total + unit;
std::cout << "Continue(c) or break(q): ";
std::cin >> quit;
} while(quit != 'q');
avg = avg / total;
std::cout << "gpa :" << " " << avg;
return 0;
}
I'm writing a program for my C++ class I've complete the program. but it won't compile. I'm new to programming so I don't really know what I'm doing wrong. If there is anyone on here that can point me in the right direction. Please help me!
Prompt Description:
Write a C++ program to calculate free estimate for carpet and furniture cleaning of residential and business customers. The program continues until end of file is reached.
Fro residential customers, specify and update number of small couches ($50 each), large couches ($80 each), rooms ($70 each) and steps ($5 each) until exit is selected. the bill is calculated based on the number of items. If the amount is more than 500 dollars, a discount of 10% is applied to the bill. Then the customer is offered to select from an installment of 1,2,3, or 4 or press 0 to exit. Based on an installment option, the bill is increased slightlenter code herey, and each installment amount is calculated.
For business customers, ask the user to enter the amount of square footage and then the bill is calculated at .45 per square foot.
Here is the code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int exit = 0;
int smallcouches = 1;
int largecouches = 2;
int rooms = 3;
int steps = 4;
const float SMALL_COUCH = 50.0;
const float LARGE_COUCH = 80.0;
const float ROOMS = 70.0;
const float STEPS = 5.00;
const float PER_SQUARE_FOOT = 0.45f;
const float DISCOUNT_QUALIFIED = 500.0;
const float DISCOUNT = 0.10f;
const int ONE = 1;
const int TWO = 2;
const int THREE = 3;
const int FOUR = 4;
const float RATEONE = 0.0f;
const float RATETWO = 0.0535f;
const float RATETHREE = 0.055f;
const float RATEFOUR = 0.0575f;
float billAmount;
float ResidentialEstimate(float SMALL_COUCH, float LARGE_COUCH, float ROOMS, float STEPS, float DISCOUNT_QUALIFIED);
void GetResidentialItems(int& smallcouches, int& largecouches, int& rooms, int& steps);
void InstallmentPlan(float billAmount);
void BusinessEstimate(float PER_SQUARE_FOOT);
int main()
{
cout << fixed << showpoint << setprecision(2);
int customerType, residential_customer, business_customer;
char B, b, R, r;
residential_customer = R || r;
business_customer = B || b;
cout << "Enter customer type: R, r (Residential) or B, b (Business): ";
cin >> customerType; //Enter customer type
cout << endl;
while (cin) //While there is input to read
{
if (customerType == R || customerType == r) //if residential customer
{
ResidentialEstimate(SMALL_COUCH, LARGE_COUCH, ROOMS, STEPS, DISCOUNT_QUALIFIED); // call function ResidentialEstimate
InstallmentPlan(billAmount); // all function Installmentplan
}
else if (customerType == B || customerType == b) //else if business customer
{
BusinessEstimate(PER_SQUARE_FOOT); //call function BusinessEstimate
}
cout << "Enter customer type: R, r (Residential) or B, b (Business): ";
cin >> customerType; // Enter cutomer type
cout << endl;
}
return 0;
}
float ResidentialEstimate(float SMALL_COUCH, float LARGE_COUCH, float ROOMS, float STEPS, float DISCOUNT_QUALIFIED)
{
GetResidentialItems(smallcouches, largecouches, rooms, steps); //Call function GetResidentialItems to get items to clean
billAmount = (SMALL_COUCH + LARGE_COUCH + ROOMS + STEPS); //Calculate the bill amount
if (billAmount > 500) //if bill amount is more than 500 dollars
{
DISCOUNT_QUALIFIED = billAmount * 0.10f;
billAmount = billAmount - DISCOUNT_QUALIFIED; //Apply a discount of 10% to the bill amount
}
return billAmount; //return bill Amount
}
void GetResidentialItems(int& smallcouches, int& largecouches, int& rooms, int& steps)
{
int count;
int choice = smallcouches || largecouches || rooms || steps;
//Ask user to select an item to update or press 0 to exit
cout << "0. Exit, 1. Small Couches, 2. Large Couches, 3. Rooms, 4. Steps " << endl;
cout << "Enter one of the above choices: ";
cin >> choice;
cout << endl;
while (choice > 0) //while user hasn't pressed 0
{
choice = count;
cout << "Please enter the number of " << choice; //ask the user to enter a number from the item selected
cin >> count;
cout << endl;
//Show the current selections and numbers
cout << "Current selections: " << count << " Small Couches, " << count << " Large Couches, " << count << " Rooms, " << count << " Steps.";
//Ask user to select an item to update or press 0 to exit
choice = 0;
count = 0;
cout << "0. Exit, 1. Small Couches, 2. Large Couches, 3. Rooms, 4. Steps " << endl;
cout << "Enter one of the above choices: ";
cin >> choice;
cout << endl;
}
}
void InstallmentPlan(float billAmount)
{
int num;
int installment = 0;
int bill = 0;
//Ask user to select number of installments or 0 to exit
cout << "Please enter the desired number of instalments (1, 2, 3, or 4) or 0 to exit : ";
cin >> num;
cout << endl;
while (num > 0) //while user hasn't pressed 0
{
//calculate the installments
if (num == 1)
installment = billAmount;
else if (num == 2)
{
bill = billAmount * 0.0535f;
installment = bill / num;
}
else if (num == 3)
{
bill = billAmount * 0.055f;
installment = bill / num;
}
else if (num == 4)
{
bill = billAmount * 0.0575f;
installment = bill / num;
}
cout << "With " << num << " installment your bill of " << billAmount << " will be worth " << bill << "." << endl;
cout << "Each installment will be worth " << installment << endl;
//Ask user to select number of installments or 0 to exit
cout << "Please enter the desired number of instalments (1, 2, 3, or 4) or 0 to exit : ";
cin >> num;
cout << endl;
}
}
void BusinessEstimate(float squarefootage)
{
//Ask user for the square footage
cout << " Enter the approximate square footage: ";
cin >> squarefootage;
cout << endl;
//Calculate the bill amount
billAmount = squarefootage * PER_SQUARE_FOOT;
cout << "Your free Business Customer Estimate for " << squarefootage << "square footage = " << billAmount;
}
Trying to fulfill the coding prompt
Input a list of positive numbers, find the mean (average) of the numbers, and output the result. Use a subprogram to input the numbers, a function to find the mean, and a subprogram to output the result.
I have done smaller calls with passing arguments but this one requires 3 separate subprograms, 1 for input, 1 for calculations and one to display the result.
So far my program is does not start the initial call for input
#include <iostream>
using namespace std;
//prototypes
int prompt(int sum, int count );
float average(int sum, int count);
void result(float avg);
int main()
{
int num;
cout << "Welcome to Keith's Averaging program";
cout << endl;
int prompt();
int average (int sum, int count);
void result (float avg);
return 0;
}
//Prototype Definitions
//get numbers from users
int prompt()
{
int num, sum, count;
cout << "Enter numbers and I will Average them." << endl;
cout << "Please enter a number: ";
cin >> num;
sum = sum + num;
if(num == 0)
{
cout << "Guess you don't want an average";
cout << endl;
cout << "Goodbye";
}
for(count=0; num !=0; count++)
{
cout << "Please enter a positive number, enter zero to compute the avg: ";
cin >> num;
if(num < 0)
{
cout << "Enter a positive number:";
cin >> num;
}
sum = sum + num;
}
Displays my welcome message then exits
I have put some comments in your code as explanation.
#include <iostream>
using namespace std;
//prototypes // These are declarations, definitions should also contain
// same function signatures
int prompt(int& sum, int& count); // accept arguments as reference (Read about it)
float average(int& sum, int& count);
void result(float& avg);
int main()
{
// int num; // don't need num in this function, not used
int sum = 0, count = 0; // create variables sum and count and initialize them to 0
float avg;
cout << "Welcome to Keith's Averaging program";
cout << endl;
prompt(sum, count); // don't need function return type and argument return type when calling
// a function
cout << sum << " " << count << endl; // print the values after prompt() call
// prompt() call must have filled the values sum and count
average(sum, count);
result(avg);
return 0;
}
//Prototype Definitions
//get numbers from users
int prompt(int& sum, int& count)
{
int num;
cout << "Enter numbers and I will Average them." << endl;
cout << "Please enter a number: ";
cin >> num;
sum = sum + num;
if(num == 0)
{
cout << "Guess you don't want an average";
cout << endl;
cout << "Goodbye";
}
for(count=0; num !=0; count++)
{
cout << "Please enter a positive number, enter zero to compute the avg: ";
cin >> num;
if(num < 0)
{
cout << "Enter a positive number:";
cin >> num;
}
sum = sum + num;
}
}
float average(int& sum, int& count){
// TODO: implement this
}
void result(float& avg) {
// TODO: implement this
}
I have changed various parts of your code. I changed the function prototypes so that they take arguments by reference.
In the int main() function, I created two variables sum and count and initialized them to 0 - we will use these variables when calling those functions.
In the int prompt() function, I changed the function signature so that it matches the declared definition (otherwise it would have been some other function). Also, I removed the local declarations sum and count since we now have them as function arguments.
I have also put the definition blocks for other two functions and you can implement them (I have marked them as // TODO).
while (counter < total)
{
inFile >> grade;
sum += grade;
counter++;
}
Above is the while loop I had for my original program and below is my attempt at converting that to a for loop.
for (counter = 0; counter < total; counter++)
{
inFile >> grade;
cout << "The value read is " << grade << endl;
total = total + grade;
}
This is a simple program to get grade averages. Here is the entire program:
#include <iostream>
#include <fstream>
using namespace std;
int average (int a, int b);
int main()
{
// Declare variable inFile
ifstream inFile;
// Declare variables
int grade, counter, total;
// Declare and initialize sum
int sum = 0;
// Open file
inFile.open("input9.txt");
// Check if the file was opened
if (!inFile)
{
cout << "Input file not found" << endl;
return 1;
}
// Prompt the user to enter the number of grades to process.
cout << "Please enter the number of grades to process: " << endl << endl;
cin >> total;
// Check if the value entered is outside the range (1…100).
if (total < 1 || total > 100)
{
cout << "This number is out of range!" << endl;
return 1;
}
// Set counter to 0.
counter = 0;
// While (counter is less than total)
// Get the value from the file and store it in grade.
// Accumulate its value in sum.
// Increment the counter.
while (counter < total)
{
inFile >> grade;
sum += grade;
counter++;
}
// Print message followed by the value returned by the function average (sum,total).
cout << "The average is: " << average(sum,total) << endl << endl;
inFile.close();
return 0;
}
int average(int a, int b)
{
return static_cast <int> (a) /(static_cast <int> (b));
}
I tried to convert while loop to a for loop but when I debug I get an infinite loop. There are no errors when I build my solution. I'm not sure what other details to add.
You are increasing the value of total in the for loop. Hence, counter never reached total if you keep entering positive values.
Perhaps you meant to use sum instead of total in the loop.
for (counter = 0; counter < total; counter++)
{
inFile >> grade;
cout << "The value read is " << grade << endl;
sum = sum + grade;
}
You are using wrong variables names, value of total is increasing in the for loop so it becomes an infinite loop, use a different variable names for storing sum and for for-loop termination condition.
I am trying to make a talent show type voting program using functions.
I have the majority of it figured out. The program prompts you to enter a name, followed by five scores, if you type "Done" rather than a name, it will close. I'm using functions for a majority of the code to practice with them.
My big issue is that there could be an infinite amount of names (as many as the user enters) and I am unaware on how to add up all 5 scores per name, I do not know how to differentiate between them. The 5 scores will be averaged and the person with the highest average of (3 scores, dropping 2) will be the winner.
Side Note: I need to drop the highest and lowest score of each person, I believe I could figure it out but an example with a function of this would be helpful to someone who is new to them.
I've researched this a lot but I could not find any examples that are similar enough to mine (having a possibly infinite amount of contestants.)
Here is my code so far, the function at the bottom is me messing around with functions to get a hang of them and see if i can get any sums of scores from a name.
#include <iostream>
#include <string>
using namespace std;
void validCheck();
void calcAvgScore();
void findHigh();
void findLow();
int main(){
int judge = 1;
double score = 0;
string name;
while (name != "done" || name != "Done"){
cout << "Enter Contestant Name, if no more, type 'done': ";
cin >> name;
if (name == "done" || name == "Done"){ break; }
for (judge = 1; judge < 6; judge++){
cout << "Enter score " << judge << " ";
validCheck();
}
}
system("pause");
return 0;
}
void validCheck(){
double score;
cin >> score;
if (score < 1 || score > 10){
cout << "Please Enter a score between 1 and 10: ";
cin >> score;
}
}
void calcAvgCheck(){
double score = 0, value = 0;
static int average;
score += value
}
Declare a string "winner", double "win_avg", double "avg" outside the while loop.
Have your validCheck() return the double value given as input (named score).
Declare a double array before your for loop (double[5] scores). Store each value returned from validCheck() into the array).
Call std::sort(std::begin(scores), std::end(scores)) to sort your scores ascending. Find the average (ignoring the max and min), and hold the max average as well as the names of the person with the max average.
#include <algorithm> // std::sort
...
double validCheck();
...
int main(){
string name;
string winner;
double win_avg;
double avg;
while (name != "done" || name != "Done"){
cout << "Enter Contestant Name, if no more, type 'done': ";
cin >> name;
double scores[5];
if (name == "done" || name == "Done"){ break; }
for (int judge = 0; judge < 5; ++judge){
cout << "Enter score " << judge << " ";
scores[judge] = validCheck();
}
std::sort(std::begin(scores), std::end(scores));
for(int score = 1; score < 4; ++score)
avg += scores[score];
avg /= 3;
if(avg > win_avg) {
winner = name;
win_avg = avg;
}
avg = 0;
}
std::cout << "Winner is: " << winner << "\n";
}
double validCheck(){
double score;
cin >> score;
if (score < 1 || score > 10){
cout << "Please Enter a score between 1 and 10: ";
cin >> score;
}
return score;
}
If you want to find the average in a function and return the value you can do this
double calcAvgCheck(const double& scores[5]) {
double avg = 0.0;
for(int score = 1; score < 4; ++score)
avg += scores[score];
avg /= 3;
return avg;
}