Need help calculating AVG of array values (minus the lowest) - c++

So I have succeeded in confusing the hell out of myself in doing this. I am trying to get it to calculate the average of the weights entered into the array minus the lowest weight in the array. I'm using functions and somewhere along the line I confused myself with passing variables. It would be much appreciated if someone could give me a pointer and tell me if I'm way off base or not. Also how would I compare the values entered to a validation code? I have a line commented out that I was fiddling with, but never got working.
#include <iostream>
using namespace std;
int getWeight();
int findLowest(int arrayWeight);
double calcAverage(int weight);
bool askToContinue();
int main(){
do{
int weights = getWeight();
double lowest = findLowest(weights);
double average = calcAverage(weights);
}
while(askToContinue());
}
int getWeight() {
//Variables
int weights[5]; //array
double enterWeight = 0;
bool validAmount = false;
//For loop to gather info and place amounts in an array
cout << "Please enter the weights of the Tulbuks: " << endl;
cout << endl;
for (int counter = 0; counter < 5; counter++)
{
cin >> weights[counter];
//validAmount = (weights[index] > 5) && (weights[index] <= 500);
}
//Test to redisplay the entered information
cout << "Entered information: " << endl;
for(int index = 0; index < 5; index++)
{
cout << "\nThe entered information for Tulbuk #" << (index+1) << " is: " << weights[index];
cout << endl;
}
return -1;
/*
do
{
//Gather user input of amount of discs
cout << "How many discs do you wish to purchase?" << endl;
cout << "Please enter a number between 1 and 1,000,000" << endl;
cin >> weights;
cout << endl;
validAmount = (weights > 5) && (weights <= 500); // Tests if the amount entered is valid
if (!validAmount) // Prompts user amount entered was invalid
{
cout << "Invalid Amount. Please try again!" << endl;
}
}
while(!validAmount); // Runs loop again if the amount entered was not valid
return discs;
*/
}
int findLowest(int arrayWeight){
int lowWeight = 999999;
if(lowWeight > arrayWeight)
{
lowWeight = arrayWeight;
}
cout << arrayWeight;
system("PAUSE");
return arrayWeight;
}
double calcAverage(int weight){
//Variables
float avgWeight = 0;
int sumWeight = 0;
//Calls findLowest function to find lowest value
int lowestWeight = findLowest(weight);
//Calculates the average score
return weight;
}
bool askToContinue() // Asks the user if they want to continue. If yes, the loop restarts. If no, the program exits.
{
char userResponse = ' ';
bool validInput = false;
do
{
cout << endl;
cout << "Do you wish to continue?" << endl;
cout << "Enter y for 'yes' or n for 'no'" << endl;
cin >> userResponse;
validInput = (userResponse == 'y') || (userResponse == 'n');
if (!validInput)
{
cout << "Invalid response. Please try again!" << endl;
}
} while (!validInput);
return(userResponse == 'y');
}

You have a number of issues, the first being you need to understand the data types you're working with. You should declare the array once and then pass around a pointer to that array. These are a better set of declarations and for convenience set up a constant for the number of weights.
#include <iostream>
using namespace std;
const int numWeights = 5;
void getWeights(int weights[]);
int findLowest(int weights[]);
double calcAverage(int weights[]);
bool askToContinue();
int main() {
do {
int weights[numWeights];
getWeights(weights);
double average = calcAverage(weights);
cout << "Average: " << average << endl;
}
while (askToContinue());
}
getWeights was mostly ok, but use the passed in array.
void getWeights(int weights[]) {
double enterWeight = 0;
bool validAmount = false;
//For loop to gather info and place amounts in an array
cout << "Please enter the weights of the Tulbuks: " << endl;
cout << endl;
for (int counter = 0; counter < 5; counter++)
{
int weight;
cin >> weight;
while (weight < 5 || weight > 500)
{
cout << "Invalid weight, should be between 5 and 500" << endl;
cin >> weight;
}
weights[counter] = weight;
//validAmount = (weights[index] > 5) && (weights[index] <= 500);
}
//Test to redisplay the entered information
cout << "Entered information: " << endl;
for(int index = 0; index < 5; index++)
{
cout << "\nThe entered information for Tulbuk #" << (index+1) << " is: " << weights[index];
cout << endl;
}
}
For findLowest you need to keep track of the lowest value and the lowest index. By remembering the index of the lowest value, you will make the average easier. Your 99999 magic number isn't needed since we know there will always be a lowest value in your set. Start with index 0 and the first value. If you find something smaller, update the value and index. When the loop ends you'll have the first index of the lowest value. Note that the loops starts at 1 (the second item).
int findLowest(int weights[]) {
int lowestVal = weights[0];
int lowestIndex = 0;
for (int i=1; i<numWeights; i++) {
if (weights[i] < lowestVal) {
lowestVal = weights[i];
lowestIndex = i;
}
}
return lowestIndex;
}
For the average find the lowest index, add up all the weights but skip the index of the lowest, convert to double so you can get a good average and return the value.
double calcAverage(int weights[]) {
int lowestIndex = findLowest(weights);
int total = 0;
for (int i=0; i<numWeights; i++) {
if (i != lowestIndex) {
total += weights[i];
}
}
return (double)total/(double)(numWeights-1);
}

Related

Creating program that takes 5 grades from the user and finds the lowest grade, and then outputs average grade after dropping the lowest grade entered

`
#include <iostream>
#include <iomanip>
using namespace std;
void getGrades(double g[], const int SIZE)
{
cout << "Please enter " << SIZE << " grades:" << endl;
for(int i = 0; i < SIZE; i++)
{
cin >> g[i];
}
}
double getAverage(double g[], const int SIZE)
{
int total = 0;
for(int i = 0; i < SIZE; i++)
{
total += g[i];
}
return total/SIZE;
}
void findDropInfo(double g[], const int SIZE, int &lowest, double average)
{
int total = 0;
lowest = g[0];
for(int i = 1; i < SIZE; i++)
{
if (lowest > g[i]) {
lowest = g[i];
}
}
average = (total - lowest)/SIZE;
return average;
}
void printData(double g[], int lowest, double average, double avg_before)
{
cout << "The 5 grades entered by the user are:" << endl;
cout << g[];
cout << "Grade dropped: " << lowest << endl;
cout << "Final Average: " << average << endl;
cout << "Average before drop: " << avg_before << endl;
}
// TODO: Complete the function definitions
int main()
{
const int SIZE = 5;
double grades[SIZE];
int lowest;
double avg,
avgBeforeDrop;
// TODO: Add function calls
getGrades(grades[SIZE], SIZE);
getAverage(grades[SIZE], SIZE);
findDropInfo(grades[SIZE], SIZE, lowest, avg);
printData(grades[SIZE], lowest, avg, avgBeforeDrop);
return 0;
}
`
Whenever I run the program, I get multiple errors saying there's no matching candidate function. I'm not sure if the problems are in the functions themselves or in the function calls, but from what I know the functions themselves should be fine. I'm also told there's an expected expression in g[] but I' not sure what's wrong there either, as it's meant to be empty.
Most issues have already been resolved in the comments, but note: cout << g[] does not print the elements of g.
The way to do this is
char separator = /* the character you want to use to separate the printed elements of g */
for (int i = 0; i < SIZE; i++)
{
cout << g[i] << separator;
}
if (separator != '\n') cout << '\n'; //this is to put the next print on the next line
I would put this as a comment but I don't have enough reputation :|

Array search and unique value addition

(Sorry if this is formatted terribly. I've never posted before.)
I've been working on a program for class for a few hours and I can't figure out what I need to do to my function to get it to do what I want. The end result should be that addUnique will add unique inputs to a list of its own.
#include <iostream>
using namespace std;
void addUnique(int a[], int u[], int count, int &uCount);
void printInitial(int a[], int count);
void printUnique(int u[], int uCount);
int main() {
//initial input
int a[25];
//unique input
int u[25];
//initial count
int count = 0;
//unique count
int uCount = 0;
//user input
int input;
cout << "Number Reader" << endl;
cout << "Reads back the numbers you enter and tells you the unique entries" << endl;
cout << "Enter 25 positive numbers. Enter '-1' to stop." << endl;
cout << "-------------" << endl;
do {
cout << "Please enter a positive number: ";
cin >> input;
if (input != -1) {
a[count++] = input;
addUnique(a, u, count, uCount);
}
} while (input != -1 && count < 25);
printInitial(a, count);
printUnique(u, uCount);
cout << "You entered " << count << " numbers, " << uCount << " unique." << endl;
cout << "Have a nice day!" << endl;
}
void addUnique(int a[], int u[], int count, int &uCount) {
int index = 0;
for (int i = 0; i < count; i++) {
while (index < count) {
if (u[uCount] != a[i]) {
u[uCount++] = a[i];
}
index++;
}
}
}
void printInitial(int a[], int count) {
int lastNumber = a[count - 1];
cout << "The numbers you entered are: ";
for (int i = 0; i < count - 1; i++) {
cout << a[i] << ", ";
}
cout << lastNumber << "." << endl;
}
void printUnique(int u[], int uCount) {
int lastNumber = u[uCount - 1];
cout << "The unique numbers are: ";
for (int i = 0; i < uCount - 1; i++) {
cout << u[i] << ", ";
}
cout << lastNumber << "." << endl;
}
The problem is my addUnique function. I've written it before as a for loop that looks like this:
for (int i = 0; i < count; i++){
if (u[i] != a[i]{
u[i] = a[i]
uCount++;
}
}
I get why this doesn't work: u is an empty array so comparing a and u at the same spot will always result in the addition of the value at i to u. What I need, is for this function to scan all of a before deciding whether or no it is a unique value that should be added to u.
If someone could point me in the right direction, it would be much appreciated.
Your check for uniqueness is wrong... As is your defintion of addUnique.
void addUnique(int value, int u[], int &uCount)
{
for (int i = 0; i < uCount; i++){
if (u[i] == value)
return; // already there, nothing to do.
}
u[uCount++] = value;
}

Using arrays and strings together

So I'm trying to create an array that contains some user inputted names, and then associate those names with letter grades from tests (ex: A, B, C, D, F). My question is, how would I use an array to accept the user inputted names?
EDIT:
Sorry this is a bit long, I don't know what part to put that would help out. Totally new to C++ and I can't seem to find anything online regarding the matter, lol.
Here is some code. This program currently asks the user for test scores, then displays and drops the lowest test score, and finally, calculates the average of the scores without the lowest one. The end goal is to ask the user for 5 students names, and 4 scores for each student, then dropping the lowest score for each student and calculating the averages of ALL scores inputted regardless of student.
#include <iostream>
#include <string>
using namespace std;
void getScore(int &);
int findLowest(int [], int);
void calcAverage(int [], int);
int main () {
const int NUM_SCORES = 5;
int scores[NUM_SCORES];
cout << "Welcome to test averages." << endl;
cout << "Please enter scores for " << NUM_SCORES << " students." << endl;
cout << endl;
for (int i = 0; i < NUM_SCORES; i++) {
getScore(scores[i]);
}
for (int i = 0; i < NUM_SCORES; i++) {
cout << "Score " << (i + 1) << ": " << scores[i] << endl;
}
cout << endl;
cout << "The lowest of these scores is " << findLowest(scores, NUM_SCORES) << endl;
calcAverage(scores, NUM_SCORES);
return 0;
}
void getScore(int & s) {
s = -1;
cout << "Please enter a test score: ";
cin >> s;
while (s < 0 || s > 100) {
cout << "Score range must be from 0-100" << endl;
cout << "Please re-enter a score: ";
cin >> s;
}
}
int findLowest(int theArray [], int theArraySize) {
int lowest = theArray[0];
for (int i = 1; i < theArraySize; i++) {
if (theArray[i] < lowest) {
lowest = theArray[i];
}
}
return lowest;
}
void calcAverage(int theArray [], int theArraySize) {
int sum = 0;
for (int i = 0; i < theArraySize; i++) {
sum += theArray[i];
}
double average = (sum - findLowest(theArray, theArraySize)) / (theArraySize - 1.0);
cout << "The average is " << average << endl;
}
Try getline from #include <string>
std::string names[5];
for (int i = 0; i < 5; ++i){
getline(std::cin, names[i]);
}

Memory Allocation Issues Passing/Returning a Struct *Array

Please help me with my homework. I've got this program working just fine in debug mode, but as soon I use release mode it crashes with an abort().
I know it probably has something to do with memory allocation, but I don't understand pointers well enough.
Requirement is that I have to use an *array to dynamically allocate memory.
"Your program should work for any number of students. When the program
starts, it should ask the user for the number of students to be
processed. Then it should dynamically allocate an array of that size
(array of student/score structures)."
I then need to, "Call a function to input the student name/score pairs and store them in the array."
So should I create the array in main or inside of the function? How can I return/pass the *array without messing up memory allocation?
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Student
{
string name; //student's name
int score; //student's score
};
//function prototypes
void inputNameScore(Student*, int&);
void sortArray(Student* , int);
double avgScore(Student* , int);
void displayTable(Student* , int, double);
int main()
{
Student* arrayOfStudentPtr; //pointer of type student to receive returned array pointer
int numberOfStudents; //number of students to be entered by user
double average; //total score average
cout << "Please enter the number of students: ";
cin >> numberOfStudents;
arrayOfStudentPtr = new Student[numberOfStudents]; //dynamic array of type Student assigned to pointer
inputNameScore(arrayOfStudentPtr, numberOfStudents);
sortArray(arrayOfStudentPtr, numberOfStudents);
average = avgScore(arrayOfStudentPtr, numberOfStudents);
displayTable(arrayOfStudentPtr, numberOfStudents, average);
return 0;
}
void inputNameScore(Student* arrayOfStudentPtr, int& numberOfStudents)
{
for (int i = 0; i < numberOfStudents; i++)
{
cout << endl << "Enter the name for student " << i + 1 << ": ";
cin.ignore();
getline(cin, arrayOfStudentPtr[i].name);
cout << endl << "Enter the student's score: ";
cin >> arrayOfStudentPtr[i].score;
while (arrayOfStudentPtr[i].score > 105 || arrayOfStudentPtr[i].score < 0)
{
cout << "Student's score can't be negative or greater than 105." << endl;
cout << endl << "Enter the student's score: ";
cin >> arrayOfStudentPtr[i].score;
}
}
}
void sortArray(Student* arrayOfStudentPtr, int numberOfStudents)
{
Student Temp; //holds a student struct object
bool swap; //swap is initialized to false at the start of each loop. If it is still false at end of loop we know there is nothing else to sort
do
{
swap = false;
for (int i = 0; i < numberOfStudents; i++)
{
if (arrayOfStudentPtr[i].score > arrayOfStudentPtr[i + 1].score)
{
Temp = arrayOfStudentPtr[i];
arrayOfStudentPtr[i] = arrayOfStudentPtr[i + 1];
arrayOfStudentPtr[i + 1] = Temp;
swap = true;
}
}
} while (swap);
}
double avgScore(Student* arrayOfStudentPtr, int numberOfStudents)
{
int total; //total of all grades
double average; //average of all grades
total = 0;
for (int i = 0; i < numberOfStudents; i++)
{
total = arrayOfStudentPtr[i].score;
}
average = total / numberOfStudents;
//average = static_cast<double>(total) / numberOfStudents;
return average;
}
void displayTable(Student* arrayOfStudentPtr, int numberOfStudents, double average)
{
cout << endl << setw(31) << left << "Name" << setw(6) << right << "Score" << endl;
cout << "-------------------------------------" << endl;
for (int i = 0; i < numberOfStudents; i++)
{
cout << setw(31) << left << arrayOfStudentPtr[i].name << setw(6) << right << arrayOfStudentPtr[i].score << endl;
}
cout << "-------------------------------------" << endl;
cout << setw(31) << left << "Average: " << setw(6) << right << endl;
}
The following code will work.
void sortArray(Student* arrayOfStudentPtr, int numberOfStudents)
{
Student Temp; //holds a student struct object
bool swap; //swap is initialized to false at the start of each loop. If it is still false at end of loop we know there is nothing else to sort
do
{
swap = false;
for (int i = 0; i < numberOfStudents-1; i++)
{
if (arrayOfStudentPtr[i].score > arrayOfStudentPtr[i + 1].score)
{
Temp = arrayOfStudentPtr[i];
arrayOfStudentPtr[i] = arrayOfStudentPtr[i + 1];
arrayOfStudentPtr[i + 1] = Temp;
swap = true;
}
}
} while (swap);
}

C++ Setting the number of array elements within a class

Hi I am working on a class for a weather station that asks a user to input variables and it passes the hours to an array: calculating the values for average, Highs and lows. I got it to work but want to make the array[elements] private. Is it possible to do this?
Here is my code so far. Thank you in advance for any help.
Brian
#include <iostream>
#include <iomanip>
using namespace std;
class WeatherStation
{
public:
WeatherStation();
void GetATemperatures(int[], int);
void DisplayATemperatures( int[], int);
void arrayCalcs(int[], int);
private:
static const int aTemps = 24;
static const int atemps[aTemps];
};
WeatherStation::WeatherStation()
{
int atemps[aTemps];
}
void WeatherStation::GetATemperatures(int atemps[], int aTemps)
{
for (int i = 0; i < aTemps; i++ )
{
cout << "Please enter the temperature for " << i << ":00 ";
while(true)
{
cin >> atemps[i];
if(atemps[i] >= -50 && atemps[i] <= 130)
{
break;
} else {
cout << "This temperature is not valid\n";
cout << "Please enter a temperature between -50 and 130 degrees F \n";
cout << "Please enter a new temperature: ";
}
}
}
}
void WeatherStation::DisplayATemperatures( int atemps[], int aTemps)
{
cout << setw (5) << "Hour" << setw(24)<< "Temperature \n";
cout << "\n";
for (int k = 0; k < aTemps; k++)
{
cout << setw (3) << k << ":00" << setw (16) << atemps[k]<<endl;
}
cout <<"\n";
}
void WeatherStation::arrayCalcs(int atemps[], int aTemps)
{
int sumA = 0;
double average = 0.0;
int minA = atemps[0];
int maxA = atemps[0];
int lowest = 0;
int highest = 0;
//Sum of the AM temps
for (int kk = 0; kk < aTemps; kk++)
{
sumA = sumA + atemps[kk];
}
//calculation for average
average = sumA / aTemps;
//Figuring out the Min and Max AM temps
for (int MM = 0; MM < aTemps; MM++)
{
if(minA > atemps[MM])
{
minA = atemps[MM];
}
else if(maxA < atemps[MM])
{
maxA = atemps[MM];
}
lowest = minA;
highest = maxA;
}
//Display of the Calculation results
cout << "This is the average of todays temperatures: " << average <<endl;
cout <<endl;
cout << "Todays High temperature is: " << highest <<endl;
cout <<endl;
cout << "Todays Low temperature is: " << lowest <<endl;
}
int main()
{
cout <<"Welcome to the weather station.\n";
cout <<"Please enter Ferenheit temperatures for calculations: \n";
WeatherStation alpha;
alpha.GetATemperatures(atemps, aTemps);
alpha.DisplayATemperatures(temps, Temps);
alpha.arrayCalcs(temps,Temps);
cout << "\n";
system("pause");
return 0;
}
1) Is the array atemps[]? If so, it's already private... what's the problem?
2) Why is your array class member static? Don't do that without damned good reason (and as this appears to be a homework assignment, I'm almost certain you don't have a damned good reason).
3) Your constructor has a useless line of code in it -- and that's the only line in the function.
4) Your professor will not accept you naming variables atemps and aTemps -- and if they do overlook it, I would be very concerned for the quality of education you're receiving. It's not that the variable names themselves are a big issue, but rather that you're naming them so similarly, as this is a recipe for a maintenance nightmare if it were to happen in real code.
Edit -- based on our comment-chat, here is my suggestion. I have not tried to compile this and I don't claim this is the best (or even a suggested) way to write your program... my suggestion is limited to leaving the data within your object (in a way that has room for growth beyond this question / discussion).
#include <iostream>
#include <iomanip>
using namespace std;
class WeatherStation
{
public:
WeatherStation();
void GetATemperatures();
void DisplayATemperatures();
void arrayCalcs();
private:
static const int aTemps = 24;
int atemps[aTemps];
};
WeatherStation::WeatherStation()
{
}
void WeatherStation::GetATemperatures()
{
for (int i = 0; i < aTemps; i++ )
{
cout << "Please enter the temperature for " << i << ":00 ";
while(true)
{
cin >> atemps[i];
if(atemps[i] >= -50 && atemps[i] <= 130)
{
break;
} else {
cout << "This temperature is not valid\n";
cout << "Please enter a temperature between -50 and 130 degrees F \n";
cout << "Please enter a new temperature: ";
}
}
}
}
void WeatherStation::DisplayATemperatures()
{
cout << setw (5) << "Hour" << setw(24)<< "Temperature \n";
cout << "\n";
for (int k = 0; k < aTemps; k++)
{
cout << setw (3) << k << ":00" << setw (16) << atemps[k]<<endl;
}
cout <<"\n";
}
void WeatherStation::arrayCalcs()
{
int sumA = 0;
double average = 0.0;
int minA = atemps[0];
int maxA = atemps[0];
int lowest = 0;
int highest = 0;
//Sum of the AM temps
for (int kk = 0; kk < aTemps; kk++)
{
sumA = sumA + atemps[kk];
}
//calculation for average
average = sumA / aTemps;
//Figuring out the Min and Max AM temps
for (int MM = 0; MM < aTemps; MM++)
{
if(minA > atemps[MM])
{
minA = atemps[MM];
}
else if(maxA < atemps[MM])
{
maxA = atemps[MM];
}
lowest = minA;
highest = maxA;
}
//Display of the Calculation results
cout << "This is the average of todays temperatures: " << average <<endl;
cout <<endl;
cout << "Todays High temperature is: " << highest <<endl;
cout <<endl;
cout << "Todays Low temperature is: " << lowest <<endl;
}
int main()
{
cout <<"Welcome to the weather station.\n";
cout <<"Please enter Ferenheit temperatures for calculations: \n";
WeatherStation alpha;
alpha.GetATemperatures();
alpha.DisplayATemperatures();
alpha.arrayCalcs();
cout << "\n";
system("pause");
return 0;
}