created a program to prompt the user to enter test scores and find the average, highest, and sort the test score. I am having problems I cant seem to get the higest test scores from the function I made and when I created the sorting test score function the program crashes. Can someone look at my functions and see where my problem is, I seem to get the average test score to show.
double getAverage(double*, int);
double gethighest(double*, int);
double getlowest(double*, int);
void arrayAscending(double*, int);
int main()
{
// Variable declarations
double *testScores; // Dynamically allocate an array of test scores
double average, highest, lowest;
int numTests; // Number of test scores
int count; // Counter variable
// Get the number of tests
cout << "How many tests do you wish to process? ";
cin >> numTests;
// Verify input is not a negative number
while (numTests <= 0)
{
// Get input again.
cout << "Please enter a positive number: ";
cin >> numTests;
}
// Dynamically allocate an array large enough to hold the test scores
testScores = new double[numTests];
// Get the specified number of test scores
cout << "Enter the test scores below.\n";
for (count = 0; count < numTests; count++)
{
cout << "Test " << (count + 1) << ": ";
cin >> *(testScores + count);
// Verify input is not a negative number
while (*(testScores + count) < 0)
{
// Get input again.
cout << "Please enter a valid test score.\n";
cin >> *(testScores + count);
}
}
// Calculate the average test score
average = getAverage(testScores, numTests);
highest = gethighest(testScores, numTests);
lowest = getlowest(testScores, numTests);
// Display the results.
arrayAscending(testScores, numTests);
cout << endl;
cout << "The average of those scores is: " << average << endl;
cout << "The higest of those scores is: " << highest << endl;
cout << "The lowest of those scores is: " << lowest << endl;
// Free dynamically allocated memory
delete[] testScores;
testScores = 0; // Make testScores point to null
return 0;
}
//function getAverage - calculates the average of the test scores
double getAverage(double* scores, int num)
{
double avg;
double total = 0.0;
for (int count = 0; count < num; count++)
{
total += scores[count];
}
avg = total / num;
return avg;
}
double gethighest(double* scores, int num)
{
double highnum = 0.0;
for (int i = 0; i < num; i++)
{
if (scores[i] > highnum)
highnum = scores[i];
}
return highnum;
}
double getlowest(double* scores, int num)
{
double lowestnum = 100;
for (int i = 0; i < num; i++)
{
if (scores[i] < lowestnum)
lowestnum = scores[i];
}
return lowestnum;
}
void arrayAscending(double *array, int size)
{
int startScan, minIndex;
double minElem;
for (startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minElem = array[startScan];
for (int index = startScan + 1; index < size; index++)
{
if ((array[index]) < minElem)
{
minElem = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minElem;
}
}
void arrayAscending(double *[], int);
should be
void arrayAscending(double *, int);
You are sorting an array of doubles, not an array of pointers to double.
Also,
double *minElem;
is used later without any memory being allocated for it. Again, you probably need just
double minElem;
and not a pointer.
If you don't need to use pointers, then use std::vector and algorithms from the standard library like std::sort.
Related
I've been working on this for hours now and I'm almost done. I can't get the program to display the correct student ID.
Also the "highIndex" function is suppose to be an "int" but I started with a double. When I try to change it, everything else seems to fall apart.
How do I get the high score to be associated with the student ID so I can output it correctly? I also need to highIndex to be an int which means some other things needs to be changed.
Any help would be much appreciated :)
Here's what I have so far
void inputAnswers(int studentIds[], double scores[]);
double getAverage(double scores[])
{
double total = 0;
for (int count = 0; count <= 6; count++)
{
total += scores[count];
}
return total / 7;
}
double highIndex(double score[])
{
double highScore = score[0];
double indexHigh = 1;
for (int count = 0; count <= 6; count++)
{
if (score[count] > highScore)
{
highScore = score[count];
indexHigh = count;
}
}
return highScore;
}
int main()
{
const int ids = 7;
int student[ids] = { 1234, 2333, 4432, 3323, 2143, 3425, 4123 };
double scores[7];
double highScore[7];
// Gets the test score from user
inputAnswers(student, scores);
// Calculates the average
cout << "The average score is " << getAverage(scores) << endl;
// Calculates highest score
cout << "The high score was student " << highIndex(highScore) << " with a score of " << highIndex(scores);
return 0;
}
// Function gets student scores
void inputAnswers(int student[], double scores[])
{
for (int count = 0; count <= 6; count++)
{
cout << "Enter the score for student "<< student[count] << ": ";
cin >> scores[count];
}
}
As per my observation you haven't supplied any values to the Highscore array and it is not required as well.
If all you need is to find average score, highscore and id of student with highscore this slight change will do the trick just adjusted 3 values from your code and is documented at corresponding lines.
#include<iostream>
using namespace std;
double getAverage(double scores[])
{
double total = 0;
for (int count = 0; count <= 6; count++)
{
total += scores[count];
}
return total / 7;
}
void inputAnswers(int student[], double scores[])
{
for (int count = 0; count <= 6; count++)
{
cout << "Enter the score for student "<< student[count] << ": ";
cin >> scores[count];
}
}
int highIndex(double score[])
{
double highScore = score[0];
double indexHigh = 0; //as we are assigning from position 0
for (int count = 1; count <= 6; count++)
{
if (score[count] > highScore)
{
highScore = score[count];
indexHigh = count;
}
}
return indexHigh; //returns index of highscore
}
int main()
{
const int ids = 7;
int student[ids] = { 1234, 2333, 4432, 3323, 2143, 3425, 4123 };
double scores[7];
//double highScore[7]; no need
// Gets the test score from user
inputAnswers(student, scores);
// Calculates the average
cout << "The average score is " << getAverage(scores) << endl;
// Calculates highest score
cout << "The high score was student " << student[highIndex(scores)] << " with a score of " << scores[highIndex(scores)]; //uses returned index to find values from array
return 0;
}
Although i strongly recommend using class or structures for such data collection of any entitiy. Happy Coding :-)
I am doing a code on tracking how much food tigers eat in 1 week and I am tracking 3 tigers.
I am supposed to print average, maximum and minimum. Whenever I run the code it doesn't print the max or minimum, only the initialized values I have in the function. I am assuming the int main() ignores my return values completely, but I can't see why is that. I have done many functions before and I do the same code every time and call it in main
Here is the code:
int main(){
cout << "Enter whether you want to find minimum for tiger 1 2 or 3. (Please
only enter 0, 1 or 2): ";
cin >> temp;
if (temp < 0) {
cout << "CAN'T RUN NEGATIVE NUMBERS";
exit(2);
}
least(food, temp, minimum);
cout << "\n";
cout << "The Tiger " << temp << " has minimum: " << minimum << " ";
cout << "\n \n ";
}
float least(float food[][DAYS], int temp, float min) //loop for days only
{
minimum = food[0][0];
//temp has to be less than 3
for (int j = 0; j < DAYS; ++j) {
if (min<food[temp][j]) {
min = food[temp][j];
}
}
cout << min << " ";
return max;
}
system("PAUSE");
return 0;
}
Since you are not using the return value, use the max and min argument as reference variable in your function definitions. Also the comparison in least & Most functions seems to be wrong. It should be the opposite way.
float least(float food[][DAYS], int temp, float &min) //loop for days only
{
min = food[0][0]; //temp has to be les
for (int j = 0; j < DAYS; ++j) {
if (min>food[temp][j]) {
min = food[temp][j];
}
}
cout << min << " ";
return min;
}
float Most(float food[][DAYS], int amb, float &max) //loop for days only
{
max = food[0][0];
//amb has to be less than 3
for (int j = 0; j < DAYS; ++j) {
if (max<food[amb][j]) {
max = food[amb][j];
}
}
cout << max << " ";
return max;
}
You do not use your methods' return values. Replace
Most(food, amb, maximum);
and
least(food, temp, minimum);
with
maximum = Most(food, amb, maximum);
and
minimum = least(food, temp, minimum);
I have a call to 2 functions which find the highest and lowest grade, respectively. they return "highestGrade" and "lowestGrade" but I am confused why the error appears when I compile. This is a lab assignment and most of the code was pre-written and I was tasked with filling in the missing code. The error occurs around lines 55 and 63, and the functions I am referring to are at the end of the code.
I am new to using arrays so I am assuming I may have some for of erroneous code inside the functions "findHighest" and "findLowest". For example, the program in "findHighest" will assume the first array it runs into is the highest grade and will compare the remaining arrays to it until it finds one that is higher. If it is, it will then assign that array to "highestGrade".
float findAverage(const GradeType, int);
int findHighest(const GradeType, int);
int findLowest(const GradeType, int);
int main()
{
GradeType grades;
int numberOfGrades;
int pos;
float avgOfGrades;
int highestGrade;
int lowestGrade;
// Read in the values into the array
pos = 0;
cout << "Please input a grade from 1 to 100, (or -99 to stop)" << endl;
cin >> grades[pos];
int i = 1;
while (grades[pos] != -99)
{
// read in more grades
pos = i;
cout << "Please input a grade from 1 to 100, (or -99 to stop)" << endl;
cin >> grades[pos];
}
numberOfGrades = pos; // Fill blank with appropriate identifier
// call to the function to find average
findAverage(grades, numberOfGrades);
avgOfGrades = findAverage(grades, numberOfGrades);
cout << endl << "The average of all the grades is " << avgOfGrades << endl;
// Fill in the call to the function that calculates highest grade
findHighest(grades, highestGrade);
highestGrade = findHighest(grades, highestGrade);
cout << endl << "The highest grade is " << highestGrade << endl;
// Fill in the call to the function that calculates lowest grade
findLowest(grades, lowestGrade);
// Fill in code to write the lowest to the screen
lowestGrade = findLowest(grades, lowestGrade);
cout << endl << "The lowest grade is " << lowestGrade << endl;
return 0;
}
float findAverage(const GradeType array, int size)
{
float sum = 0; // holds the sum of all the numbers
for (int pos = 0; pos < size; pos++)
sum = sum + array[pos];
return (sum / size); //returns the average
}
int findHighest(const GradeType array, int size)
{
// Fill in the code for this function
float highestGrade = array[0];
for (int i = 0; i < size; i++)
{
if (array[i] > highestGrade)
highestGrade = array[i];
}
return highestGrade;
}
int findLowest(const GradeType array, int size)
{
// Fill in the code for this function
float lowestGrade = array[0];
for (int i = 1; i < size; i++)
{
if (array[i] < lowestGrade)
lowestGrade = array[i];
}
return lowestGrade;
}
The program is unable to output the highest and lowest grade due to the error.
findLowest(grades, lowestGrade);
You are using lowestGrade before initializing it.
int lowestGrade;
should be
int lowestGrade = 0; // or to anything that has meaning for your app.
And of course, as better C++, declare it just before you need it, not at the top of the function.
Same thing for the other variables.
All of this of course if the logic is correct. Why do you pass the lowest/higest grade as a size parameter in the functions?
When I enter the following value for each question it ask for the user input, the average is not correct. Values I enter are 3 for the amount of testscores, 64,90,52 for the score for each test score. My debugger shows 52 as my lowest drop test score so I do not believe the issue is the LowestTestScore function, but it's the calculate the average test score. The line below should give me the average of just only the two testscores (64,90). average =(total/size-1); // Average with the drop lowest test score is wrong If someone could guide me to the right direction I would gladly appreciated. I posted the entire source code because I was not sure if you could be able to figure out what is wrong with it with just snippets of the code. The sort function works as it should work, The main function works as it should as well. I believe the lowest function works too since it's giving me the correct output as my lowest testgrade.
#include <iostream>
void sortAscendingOrder(int*, int );
void LowestTestScore(int*, int);
void calculatesAverage(int*,int);
int main()
{
int* array = nullptr;
int input;
std::cout << "Enter the number of testscores you want to enter." <<std::endl;
std::cin >> input;
array = new int[input];
for(int count =0; count < input; count++)
{
std::cout << "Enter the test score" << (count +1) <<":" <<std::endl;
std::cin >> *(array+count);
while(*(array+count) < 0)
{
std::cout <<"You enter a negative number. Please enter a postive number." <<std::endl;
std::cin >> *(array+count);
}
}
sortAscendingOrder(array,input);
for(int count =0; count < input;count++)
{
std::cout << "\n" << *(array+count);
std::cout << std::endl;
}
LowestTestScore(array,input);
calculatesAverage(array,input);
return 0;
}
void sortAscendingOrder(int* input,int size)
{
int startScan,minIndex,minValue;
for(startScan =0; startScan < (size-1);startScan++)
{
minIndex = startScan;
minValue = *(input+startScan);
for(int index = startScan+1;index<size;index++)
{
if(*(input+index) < minValue)
{
minValue = *(input+index);
minIndex = index;
}
}
*(input+minIndex)=*(input+startScan);
*(input+startScan)=minValue;
}
}
void LowestTestScore(int* input, int size)
{
int count =0;
int* lowest = nullptr;
lowest = input;
for(count =1; count <size;count++)
{
if(*(input+count) < lowest[0])
{
lowest[0] = *(input+count);
}
}
std::cout << "Lowest score" << *lowest;
}
void calculatesAverage(int* input, int size)
{
int total = 0;
int average =0;
for(int count = 0; count < size; count++)
{
total += *(input+count);
}
average =(total/size-1); // Average with the drop lowest test score is wrong.
std::cout << "Your average is" << average;
}
To average after dropping the lowest test score, change
void LowestTestScore(int* input, int size)
{
int count =0;
int* lowest = nullptr;
lowest = input;
for(count =1; count <size;count++)
{
if(*(input+count) < lowest[0])
{
lowest[0] = *(input+count);
}
}
std::cout << "Lowest score" << *lowest;
}
To (notice '*lowest = 0;' at the bottom):
void LowestTestScore(int* input, int size)
{
int count =0;
int* lowest = nullptr;
lowest = input;
for(count =1; count <size;count++)
{
if(*(input+count) < lowest[0])
{
lowest[0] = *(input+count);
}
}
std::cout << "Lowest score" << *lowest;
*lowest = 0;
}
Then in your calculatesAverage function, make sure you calculate the average like:
average =(total/(size-1));
so the program needs to dynamically allocate an array large enough to hold a user=defined number of test scores. once all scores are entered, the array should be passed to a function that sorts them in ascending order. another function should be called that calculates the average score. the program should display the sorted list of scores and averages with appropriate headings. use pointer notation rather than array notation whenever possible.
the problem i am having is making it so that the program doesn't accept negative numbers for test scores.
here is the code.
source.cpp
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
void arrSelectSort(float *, int);
void showArrPtr(float *, int);
void showAverage(float, int);
int main()
{
float *scores, //To dynamically allocate an array
total = 0.0, //Accumulator
average; //To hold the averge scores
int numScores; //To hold the number of test scores
//Get the number of test scores.
cout << "How many test scores would you like to process?";
cin >> numScores;
//Dynamically allocate an array large enough to hold that many
//test scores
scores = new float[numScores];
if (scores == NULL)
return 0;
//Get the test score for each test
cout << "Enter the test scores below.\n";
for (int count = 0; count < numScores; count++)
{
cout << "Test score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores <= 0)
{
cout << "Zero or negative numbers not accepted.\n";
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
}
}
//Calculate the total scores
for (int count = 0; count < numScores; count++)
{
total += scores[count];
}
//sort the elements of the array pointers
arrSelectSort(scores, numScores);
//Will display them in sorted order.
cout << "The test scores in ascending order are: \n";
showArrPtr(scores, numScores);
showAverage(total, numScores);
//Free memory.
delete[] scores;
return 0;
}
void arrSelectSort(float *array, int size)
{
int startScan, minIndex;
float minElem;
for (startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minElem = array[startScan];
for (int index = startScan + 1; index < size; index++)
{
if (array[index] < minElem)
{
minElem = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minElem;
}
}
void showArrPtr(float *array, int size)
{
for (int count = 0; count< size; count++)
cout << array[count] << " ";
cout << endl;
}
void showAverage(float total, int numScores)
{
float average;
//Calculate the average
average = total / numScores;
//Display the results.
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << average << endl;
system("pause");
}
modified source.cpp to use double instead of float
#include <iostream>
#include <iomanip>
using namespace std;
void arrSelectSort(double *, int);
void showArrPtr(double *, int);
double showAverage(double, int);
int main()
{
double *scores, //To dynamically allocate an array
total = 0.0, //Accumulator
average; //To hold the averge scores
int numScores; //To hold the number of test scores
//Get the number of test scores.
cout << "How many test scores would you like to process?";
cin >> numScores;
//Dynamically allocate an array large enough to hold that many
//test scores
scores = new double[numScores];
if (scores == NULL)
return 0;
//Get the test score for each test
cout << "Enter the test scores below.\n";
for (int count = 0; count < numScores; count++)
{
cout << "Test score #" << (count + 1) << ": ";
cin >> scores[count];
while (scores[count] <= 0)
{
cout << "Zero or negative numbers not accepted.\n";
cout << "Test Score #" << (count + 1) << ": ";
cin >> scores[count];
}
}
//Calculate the total scores
for (int count = 0; count < numScores; count++)
{
total += scores[count];
}
//sort the elements of the array pointers
arrSelectSort(scores, numScores);
cout << "The test scores in ascending order are: \n";
showArrPtr(scores, numScores);
showAverage(total, numScores);
delete[] scores;
return 0;
}
void arrSelectSort(double *array, int size)
{
int startScan, minIndex;
double minElem;
for (startScan = 0; startScan < (size - 1); startScan++)
{
minIndex = startScan;
minElem = array[startScan];
for (int index = startScan + 1; index < size; index++)
{
if (array[index] < minElem)
{
minElem = array[index];
minIndex = index;
}
}
array[minIndex] = array[startScan];
array[startScan] = minElem;
}
}
void showArrPtr(double *array, int size)
{
for (int count = 0; count< size; count++)
cout << array[count] << " ";
cout << endl;
}
double showAverage(double total, int numScores)
{
double average;
//Calculate the average
average = total / numScores;
//Display the results.
cout << fixed << showpoint << setprecision(2);
cout << "Average Score: " << average << endl;
system("pause");
}
errors -
Severity Code Description Project File Line Suppression State
Error C4716 'showAverage': must return a value ConsoleApplication9 c:\users\kenny\desktop\kenny_fepc1.cpp 85
Severity Code Description Project File Line Suppression State
Warning C4101 'average': unreferenced local variable ConsoleApplication9 c:\users\kenny\desktop\kenny_fepc1.cpp 12
please help fix. thank you.
You are not checking for the value that was input:
while (scores <= 0)
should be
while (scores[count] <= 0)
I guess this is homework and you are requested to use c-style arrays. However, please note that using a std::vector would make the task very much simpler as it has a dynamic size (that you dont have to handle "manually") and sorting a vector is trivial.
Btw I would suggest you to change the loop to
for (int count = 0; count < numScores; count++) {
scores[count] = -1;
while (scores[count] <= 0) {
cout << "Test Score #" << (count + 1) << "(has to be >0) : ";
cin >> scores[count];
}
}
Duplicate code is always a pain in the ass when you want to make changes to the code. Try to avoid it whenever possible (even if it is only two small lines).
Your other error appears because your showAverage is declared to return a double but it has no return. Either declare it to return nothing:
void showAverage(double total, int numScores)
or add a return statement at the end of the function:
return average;