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;
}
Related
The final result cannot be displayed.
/*A Teacher has five students who have taken four tests. The teacher uses the following grading scale to assign a letter grade to a student, based on the average of his or her four test scores:
90-100 A
80-89 B
70-79 C
60-69 D
0-59 F
Write a program that uses an array of string objects to hold the five students' names, an array of five characters to hold the five students' letter grades, and five arrays of four doubles each to hold each student's set of test scores. enter code here
The program should allow the user to enter each student's name, and his or her four test scores. It should then calculate and display each student’s average test score, and a letter grade based on the average.
Input Validation: Do not accept test scores less than zero or greater than 100.*/
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const int SUBJECT=4,STUDENT=5;
string name[5];
char grade[5];
double score[SUBJECT][STUDENT];
double average[5];
int i,j,k,l;
for (k=0;k<STUDENT;k++)
{
cout<<"Enter the name of student "<<k+1<<":"<<endl;
getline(cin,name[k]);
}
for (i=0;i<STUDENT;i++)
{
double sum=0;
for (j=0;j<SUBJECT;j++)
{
cout<<"Enter the test scores of subject "<<j+1<<" for "<<name[i]<<":";
cin >> score[i][j];
while (score[i][j] < 0||score[i][j] > 100)
{
cout<<"Invalid test score! Test scores can't be less than 0 or greater than 100."<<endl;
cout<<"Enter again the test scores of subject "<<j+1<<":";
cin >> score[i][j];
}
sum+=score[i][j];
average[i]=sum / SUBJECT;
}
}
cout<<setw(30)<<"Student's name"<<setw(25)<<"Average test score"<<setw(15)<<"Letter Grade"<<endl;
cout<<"------------------------------------------------------------------------------------------"<<endl;
for (l=0;l<STUDENT;l++)
{
if (average[l]>=90)
{
grade[l]='A';
}
else if (average[l]<90 && average[l]>=80)
{
grade[l]='B';
}
else if (average[l]<80 && average[l]>=70)
{
grade[l]='C';
}
else if (average[l]<70 && average[l]>=60)
{
grade[l]='D';
}
else
{
grade[l]='F';
}
cout<<setw(30)<<name[l]<<setw(25)<<average[l]<<setw(9)<<grade[l];
}
return 0;
}
The final result name,average and grade did not be displayed before the program terminated.
There are several issues in your code :
In this line cin >> score[i][j]; , i is related to a student and j is related to a subject, while the declaration was score[SUBJECT][STUDENT]
the average must be calculated after the subject loop
you should avoid magic constants, like in name[5]
It is better to avoid using namespace std;
It is better to better encapsulate variables such as i, j, and therefore not to declare them as global
This is a working example. Note that the final output still needs to be optimised but I let you do it!
#include <iostream>
#include <iomanip>
#include <string>
//using namespace std;
int main()
{
const int SUBJECT = 4,STUDENT = 5;
std::string name[STUDENT];
char grade[STUDENT];
double score[STUDENT][SUBJECT];
double average[STUDENT];
for (int i = 0; i < STUDENT;i++)
{
std::cout << "Enter the name of student " << i+1 << " : " << std::endl;
getline (std::cin,name[i]);
}
for (int i = 0; i < STUDENT; i++)
{
double sum = 0;
for (int j = 0; j < SUBJECT; j++)
{
std::cout << "Enter the test scores of subject "<<j+1<<" for "<<name[i]<<": ";
std::cin >> score[i][j];
while (score[i][j] < 0||score[i][j] > 100)
{
std::cout<<"Invalid test score! Test scores can't be less than 0 or greater than 100." << "\n";
std::cout<<"Enter again the test scores of subject " << j+1 << ": ";
std::cin >> score[i][j];
}
sum += score[i][j];
}
average[i] = sum / SUBJECT;
}
std::cout << std::setw(30) << "Student's name" << std::setw(25) << "Average test score" << std::setw(18) << "Letter Grade" << "\n";
std::cout<<"------------------------------------------------------------------------------------------" << "\n";
for (int i = 0;i < STUDENT; i++)
{
if (average[i]>=90)
{
grade[i]='A';
}
else if (average[i]<90 && average[i]>=80)
{
grade[i]='B';
}
else if (average[i]<80 && average[i]>=70)
{
grade[i]='C';
}
else if (average[i]<70 && average[i]>=60)
{
grade[i]='D';
}
else
{
grade[i]='F';
}
std::cout<<std::setw(30)<<name[i]<<std::setw(25)<<average[i]<<std::setw(20)<<grade[i]<<"\n";
}
return 0;
}
How about adding a <<endl statement to the last cout expression. This should flush the internal buffer to the output.
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.
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.
I'm pretty new to C++, only had experience in C#, Python, and JS so bear with me!
I am taking the user's input on 5 scores and storing it in an array. I pass the array off and evaluate the scores in the array to find the lowest value and highest value. I need to drop those two, then find the average of the other 3 values. My problem is, I'm not finding the highest/lowest value. I have the logic in findLowest() and findHighest() but to test it I put the same logic in main() to see if its working before its passed off, and its not working. Can someone guide me to finding the highest/lowest values in the array? Thanks!
#include "stdafx.h"
#include <iostream>
#include <cmath>
#include <iomanip>
#include <algorithm>
using namespace std;
void getJudgeData(double score)
{
cin >> score;
if (score > 10 || score < 0)
{
cout << "Invalid score, please enter again." << endl;
cin >> score;
}
else
{
cout << "Thank you." << endl;
}
}
double findLowest(double scores[])
{
double lowScore = *min_element(scores, scores+5);
return lowScore;
}
double findHighest(double scores[])
{
double highScore = *max_element(scores, scores+5);
return highScore;
}
double calcScore(double scores[])
{
double finalScore;
double sum = 0;
double newScore[3] = {};
double lowScore = findLowest(scores);
double highScore = findHighest(scores);
int j = 0;
for (int i=0; i < 5; i++)
{
if (scores[i] != lowScore && scores[i] != highScore)
{
scores[i] = newScore[j];
j++;
}
}
for (int k=0; k < 3; k++)
{
sum = sum + newScore[k];
}
finalScore = sum/3;
return finalScore;
}
int main()
{
double finalScore;
double judgeScores[5] = {};
for (int i = 0; i < 5; ++i)
{
cout << "Enter judge " << i + 1 << "'s score: ";
getJudgeData(judgeScores[i]);
}
finalScore = calcScore(judgeScores);
cout << "Highest score is: " << *max_element(judgeScores, judgeScores+5) << endl;
cout << "The final score is: " << finalScore << endl;
// This prevents the Console Window from closing during debug mode
cin.ignore(cin.rdbuf()->in_avail());
cout << "\nPress only the 'Enter' key to exit program: ";
cin.get();
return 0;
}
This is because getJudgeData takes double score by value. As the result, the entries by the end user remain confined to the getJudgeData function; the judgeScores[i] variable that you pass to the function remains unchanged.
Add an ampersand to fix this problem:
void getJudgeData(double &score) {
...
}
Now the parameter is passed by reference, letting getJudgeData make modifications to it.
Change
void getJudgeData(double score)
to
void getJudgeData(double &score)
It looks like most of your logic is OK, except you have your assignment swapped in calcScore(). You have:
scores[i] = newScore[j];
You probably meant:
newScore[j] = scores[i];
Also, be wary: If your input array contains multiple scores equal to the minimum or maximum, you will have less than 3 remaining after you remove them.
Edit: Oh yeah, and also what others have said about passing the value by reference to getJudgeData().
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.