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().
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.
Having trouble with the function call for monthlyAverage() function because I do not know what to pass through in order for it to work.
// Zachary Fernandez
// Term Project Part II
// TP21_rainfall_statisitcs.cpp
#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;
void userInput(double rainfall[]);
double totalRainfall(double rainfall[]);
double monthlyAverage(double sum);
int main()
{
double rainfall[12];
cout << "Please enter the rainfall of each month of the year\n";
cout << "seperated by a space.\n";
userInput(rainfall);
totalRainfall(rainfall);
monthlyAverage();
system("pause");
return 0;
}
void userInput(double rainfall[])
{
for (int i = 0; i < 12; i++)
{
cin >> rainfall[i];
}
}
double totalRainfall(double rainfall[])
{
double sum = 0;
for (int i = 0; i < 12; i++)
{
sum += rainfall[i];
}
cout << "The total amount of rainfall for the year is: ";
cout << sum;
cout << endl;
return sum;
}
Having trouble with this function because the function call is not allowing me to pass anything through. I also do not know what to pass through in order for it to work.
double monthlyAverage(double sum)
{
double average;
average = (sum / 12);
cout << "The average monthly rain fall is: ";
cout << average;
cout << endl;
return average;
}
I think you would need something like this:
int main()
{
double rainfall[12];
cout << "Please enter the rainfall of each month of the year\n";
cout << "seperated by a space.\n";
userInput(rainfall);
double total = totalRainfall(rainfall);
double avg = monthlyAverage(total);
cout << "Monthly Average:" << avg << endl;
system("pause");
return 0;
}
Well you declared it to take in a double, so any double value will work. I am assuming sum means total rainfall, so you can either store the value of the totalRainfall() function in a variable, then pass the variable, or do something like
int average = monthlyAverage(totalRainfall(rainfall));
This will use the value returned by the totalRainfall function and pass it into monthlyAverage, then store the result into int average.
Since your totalRainfall method prototype is - double totalRainfall(double rainfall[]), it means the function is returning a double value which you can pass to monthlyAverage function.
double total = totalRainfall(rainfall);
double avg = monthlyAverage(total);
You can store the return value in a variable (avg in the example) as shown above.
This function takes one double Argument
double monthlyAverage(double sum);
So you must pass a double value in order to work.Like
monthlyAverage(100.5);
In your case it is look like this
monthlyAverage(totalRainfall(rainfall));
Looking at your context, this exercise (?) seem to suggest that you write
monthlyAverage(totalRainfall(rainfall));
Why? you see that totalRainfall returns a double, and it passes to monthlyAverage to output the average.
By the way, your system("pause"); is not very portable.
Say, Apple version is different.
I do not have any error but when I run the program sales name 1 not print out. I am using C++.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void getData(string names[],double sales[3][4]); void
calTotalSales(string names[],double sales[3][4]);
int main() { double sales[3][4]; string names[3];
getData(names,sales);
calTotalSales(names,sales); return 0; }
void getData(string names[],double sales[3][4]) {
for(int i=0;i<3;i++) {
cout<<"Enter in the name of the salesman "<<i+1<<": ";
cin>>names[i];
cout<<"Now Enter in the sales for each quarter for "<<names[i]<<endl;
for(int j=0;j<4;j++)
{
cout<<"Enter in the data for the quarter "<<j+1<<": ";
cin>>sales[i][j];
}
cout<<endl; } }
void calTotalSales(string names[],double sales[3][4]) {
double max; string name; int i;
cout << setprecision(2) << fixed;
for(int j=0;j<4;j++)
{
max = sales[0][j];
for(i = 0; i < 3; i ++)
{
if(max < sales[i][j])
{
max = sales[i][j];
name = names[i];
}
}
cout << "name is " << name << endl;
cout << "Salesman " << name << " had the highest sale for the quarter " << j + 1 << " with $" << max << endl; } }
First some things, i assume that you are a beginner in c++ so i will give you some advice if you dont mind, avoid to use using namespace std try not to get used, here there is a explanation about why you should not use it,and this is just because i am a bit obsessive but try to format your code better it will make easier to understand every part.
Now the important part, your code works perfectly but "sales name 1" does not print because once you set max here : max = sales[0][j]; in case that this position is actually the max it will never enter in this if :
if(max < sales[i][j])
{
max = sales[i][j];
name = names[i];
}
So if it never enters in that if name will never be changed and thats why it does not print sales name 1 , so the solution is as simple as this changes where you set the max = sales[0][j] for this :
max = sales[0][j];
name = names[0];
Adding this last line will fix your problem.
Sorry if i didnt explain myself enough clearly (its my first answer :P)
Basically what I am trying to do is get the lowest number, but the program is feeding me back garbage, but I use the same line of code to get the highest value, only change I made was > to <, the program gives me back the highest value no problem put not the lowest. And I have tried everything I can think of from making the lowest= x[0], lowest=101( user is suppose to enter in grades on scale of 0-100, thought made it had something to do with the value. ) and lowest =highest and it still give me back a number like -9.255596e...., any help or suggestion or greatly appreciated, or maybe a point in the right direction just really trying to understand why it works for one set of numbers and not the others.
#include "stdafx.h"
#include <iostream>
using std::cout;
using std::endl;
using std::cin;
double average(double,int);
double sum1(double[],int);
double highest(double[], int);
double lowest(double[], int);
int _tmain(int argc, _TCHAR* argv[])
{
double gradeBook[1000];
char x;
int count = 0;
cout << "Do you wish to start the program if so enter y to stop enter q" << endl;
cin >> x;
while (x != 'q')
{
cout << "Enter in test grade on a scale of 0 to 100" << endl;
cin >> gradeBook[count];
if (gradeBook[count]<0 || gradeBook[count]>100)
{
cout << " Please try again ";
count--;
}
else
cout << "valid answer" << endl;
count++;
cout << "Do you wish to continue entering in grades? If so enter y to stop enter q" << endl;
cin >> x;
}
highest(gradeBook, count);
cout << "The highest grade enter is " << highest(gradeBook, count) << endl;
lowest(gradeBook, count);
cout << "The lowest grade enter is " << lowest(gradeBook, count) << endl;
cout << lowest <<endl;
return 0;
}
double highest(double x[], int y)
{
double highest = 0;
for (int i = 0; i<= y; i++)
{
if (x[i]>highest)
highest = x[i];
}
return highest;
}
double lowest(double x[], int y)
{
double lowest = 100;
for (int i = 0; i<= y; i++)
{
if (x[i]< lowest)
lowest = x[i];
}
return lowest;
}
A way to resolve your question is to use code already tested.
In your case you can use min_element and max_element to find min and max element of your code:
cout << "The highest grade enter is " << *max_element(gradeBook,
gradeBook+count) << endl;
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;
}