C++ struct, function can't print smallest diameter - c++

This is my code so far the problem I am having is with it printing out the smallest diameter of the planet.
Update Code....and still don't work...
#include <iostream>
#include <string>
using namespace std;
struct Planet
{
string name;
int distanceSun;
int diameter;
int mass;
};
int PrintPlanet(Planet planet)
{
cout << "Name: " << planet.name << endl;
cout << "Distance to the sun: " << planet.distanceSun << endl;
cout << "Diameter: " << planet.diameter << endl;
cout << "Mass: " << planet.mass << endl;
return 0;
}
int FindSmallestDiameter(Planet * arr, int n)
{
int resultSmallest = INT_MAX;
for (int j = 1; j < n; j++)
{
if(arr[j].diameter < arr[resultSmallest].diameter)
{
resultSmallest = j;
}
}
return resultSmallest;
}
int main()
{
struct Planet * planet;
int numberPlanet;
cout << "Enter a value for planets: ";
cin >> numberPlanet;
planet = new Planet[numberPlanet];
int enterSelection;
do
{
cout << "Enter selection: \n" <<
"1. Print the planet with the smallest diameter\n" <<
"0. Exit progrma\n";
cin >> enterSelection;
switch(enterSelection)
{
case 1:
{
int heaviest = FindHeaviestPlanet(planet, numberPlanet);
if (heaviest < 0)
{
cout << "No planet defined.\n";
}
else
{
cout << "Heaviest planet: \n";
PrintPlanet(planet[heaviest]);
}
}
break;
}
'
When in the menu set the print command on the planet with the smaller diameter console print:
Name:
Distance to the sun: 0
Diameter: 0
Mass: 0

Regardless of the missing code in main(), the syntactic errors there, and the way you could populate the planets, your search function FindSmallestDiameter() will never work:
you start with resultSmallest = INT_MAX. This is a very very large number
then you start your loop with j=1 (normally array indexing startw with 0)
then you try to access arr[resultSmallest].diameter, which is out of bounds, and causes undefined behaviour. It could cause havoc or segmentation faults, but it could also return a random number, or even 0.
Note that this function will never return a negative number, even if the planet array is empty. So your message "No planet defined" will never be displayed. Even worse, if no planet is defined, you'll return INT_MAX, which could cause your code in main() to (try to) access further elements out of bounds.
Possible correction:
int FindSmallestDiameter(Planet * arr, int n)
{
if (n==0)
return -1; // handle special case first
else {
int resultSmallest = 0; // let's suppose the smallest is the first element
for (int j = 1; j < n; j++) { // then it makes sense to loop starting with the second
if(arr[j].diameter < arr[resultSmallest].diameter) // and challenge the current smalest
resultSmallest = j;
}
return resultSmallest;
}
}
Or a shorter one, using standard algorithm std::min_element():
int FindSmallestDiameter(Planet * arr, int n)
{
return n==0 ? -1 : std::min_element(arr,arr+n,[](const Planet &a,const Planet &b)->bool {return a.diameter<b.diameter;})-arr;
}

The problem is solved with the following function:
Planet FindSmallestDiameter(Planet * arr, int n)
{
Planet smallestDiameter = arr[0];
for (int i = 0; i < n; i++)
{
if (smallestDiameter.diameter < arr[i].diameter)
{
smallestDiameter = arr[i];
}
}
return smallestDiameter;
}

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 :|

How would you go about resolving this output value?

I finished this code homework assignment tonight. I thought I was done, but I just realized that my "Average" value is coming out wrong with certain values. For example: When my professor entered the values 22, 66, 45.1, and 88 he got an "Average" of 55.27. However, when I enter those values in my program, I get an "Average" of 55.25. I have no idea what I am doing wrong. I was pretty confident in my program until I noticed that flaw. My program is due at midnight, so I am clueless on how to fix it. Any tips will be greatly appreciated!
Code Prompt: "Write a program that dynamically allocates an array large enough to hold a user-defined number of test scores. Once all the 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."
Professor Notes: The book only states, "Input Validation: Do not accept negative numbers for test scores." We also need to have input validation for the number of scores. If it is negative, including 0, the program halts, we should consider this situation for 'counter' not to be negative while we have a loop to enter numbers. So negative numbers should be rejected for the number of scores and the values of scores.
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
void showArray(double* array, int size);
double averageArray(double* array, int size);
void orderArray(double* array, int size);
int main()
{
double* scores = nullptr;
int counter;
double numberOfScores;
cout << "\nHow many test scores will you enter? ";
cin >> numberOfScores;
if (numberOfScores < 0) {
cout << "The number cannot be negative.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
if (numberOfScores == 0) {
cout << "You must enter a number greater than zero.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
scores = new double[numberOfScores];
for (counter = 0; counter < numberOfScores; counter++) {
cout << "Enter test score " << (counter + 1) << ": ";
cin >> *(scores + counter);
if (*(scores + counter) < 0) {
cout << "Negative scores are not allowed. " << endl
<< "Enter another score for this test : ";
cin >> *(scores + counter);
}
}
orderArray(scores, counter);
cout << "\nThe test scores in ascending order, and their average, are: " << endl
<< endl;
cout << " Score" << endl;
cout << " -----" << endl
<< endl;
showArray(scores, counter);
cout << "\nAverage Score: "
<< " " << averageArray(scores, counter) << endl
<< endl;
cout << "Press any key to continue...";
delete[] scores;
scores = nullptr;
system("pause>0");
}
void orderArray(double* array, int size)
{
int counterx;
int minIndex;
int minValue;
for (counterx = 0; counterx < (size - 1); counterx++) {
minIndex = counterx;
minValue = *(array + counterx);
for (int index = counterx + 1; index < size; index++) {
if (*(array + index) < minValue) {
minValue = *(array + index);
minIndex = index;
}
}
*(array + minIndex) = *(array + counterx);
*(array + counterx) = minValue;
}
}
double averageArray(double* array, int size)
{
int x;
double total{};
for (x = 0; x < size; x++) {
total += *(array + x);
}
double average = total / size;
return average;
}
void showArray(double* array, int size)
{
for (int i = 0; i < size; i++) {
cout << " " << *(array + i) << endl;
}
}
I try to start my answers with a brief code review:
#include <iostream>
#include <iomanip>
using namespace std; // Bad practice; avoid
void showArray(double* array, int size);
double averageArray(double* array, int size);
void orderArray(double* array, int size);
int main()
{
double* scores = nullptr;
int counter;
double numberOfScores;
cout << "\nHow many test scores will you enter? ";
cin >> numberOfScores;
// This is not input validation, I can enter two consecutive bad values,
// and the second one will be accepted.
if (numberOfScores < 0) {
// Weird formatting, this blank line
cout << "The number cannot be negative.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
// The homework, as presented, doesn't say you have to treat 0 differently.
if (numberOfScores == 0) {
cout << "You must enter a number greater than zero.\n"
<< "Enter another number: ";
cin >> numberOfScores;
}
scores = new double[numberOfScores];
// Declare your loop counter in the loop
for (counter = 0; counter < numberOfScores; counter++) {
cout << "Enter test score " << (counter + 1) << ": ";
cin >> *(scores + counter);
if (*(scores + counter) < 0) {
cout << "Negative scores are not allowed. " << endl
<< "Enter another score for this test : ";
cin >> *(scores + counter);
}
}
orderArray(scores, counter); // Why not use numberOfScores?
cout << "\nThe test scores in ascending order, and their average, are: " << endl
<< endl;
cout << " Score" << endl;
cout << " -----" << endl
<< endl;
showArray(scores, counter); // Same as above.
cout << "\nAverage Score: "
<< " " << averageArray(scores, counter) << endl
<< endl;
cout << "Press any key to continue...";
delete[] scores;
scores = nullptr;
system("pause>0"); // Meh, I suppose if you're on VS
}
void orderArray(double* array, int size)
{
int counterx;
int minIndex;
int minValue; // Unnecessary, and also the culprit
// This looks like selection sort
for (counterx = 0; counterx < (size - 1); counterx++) {
minIndex = counterx;
minValue = *(array + counterx);
for (int index = counterx + 1; index < size; index++) {
if (*(array + index) < minValue) {
minValue = *(array + index);
minIndex = index;
}
}
*(array + minIndex) = *(array + counterx);
*(array + counterx) = minValue;
}
}
double averageArray(double* array, int size)
{
int x;
double total{};
for (x = 0; x < size; x++) {
total += *(array + x);
}
double average = total / size;
return average;
}
void showArray(double* array, int size)
{
for (int i = 0; i < size; i++) {
cout << " " << *(array + i) << endl;
}
}
When you are sorting your array, you keep track of the minValue as an int and not a double. That's why your average of the sample input is incorrect. 45.1 is truncated to 45 for your calculations. You don't need to keep track of the minValue at all. Knowing where the minimum is, and where it needs to go is sufficient.
But as I pointed out, there are some other serious problems with your code, namely, your [lack of] input validation. Currently, if I enter two consecutive bad numbers, the second one will be accepted no matter what. You need a loop that will not exit until a good value is entered. It appears that you are allowed to assume that it's always a number at least, and not frisbee or any other non-numeric value.
Below is an example of what your program could look like if your professor decides to teach you C++. It requires that you compile to the C++17 standard. I don't know what compiler you're using, but it appears to be Visual Studio Community. I'm not very familiar with that IDE, but I imagine it's easy enough to set in the project settings.
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <string>
#include <vector>
// Assumes a number is always entered
double positive_value_prompt(const std::string& prompt) {
double num;
std::cout << prompt;
do {
std::cin >> num;
if (num <= 0) {
std::cerr << "Value must be positive.\n";
}
} while (num <= 0);
return num;
}
int main() {
// Declare variables when you need them.
double numberOfScores =
positive_value_prompt("How many test scores will you enter? ");
std::vector<double> scores;
for (int counter = 0; counter < numberOfScores; counter++) {
scores.push_back(positive_value_prompt("Enter test score: "));
}
std::sort(scores.begin(), scores.end());
for (const auto& i : scores) {
std::cout << i << ' ';
}
std::cout << '\n';
std::cout << "\nAverage Score: "
<< std::reduce(
scores.begin(), scores.end(), 0.0,
[size = scores.size()](auto mean, const auto& val) mutable {
return mean += val / size;
})
<< '\n';
}
And here's an example of selection sort where you don't have to worry about the minimum value. It requires that you compile to C++20. You can see the code running here.
#include <iostream>
#include <random>
#include <vector>
void selection_sort(std::vector<int>& vec) {
for (int i = 0; i < std::ssize(vec); ++i) {
int minIdx = i;
for (int j = i + 1; j < std::ssize(vec); ++j) {
if (vec[j] < vec[minIdx]) {
minIdx = j;
}
}
int tmp = vec[i];
vec[i] = vec[minIdx];
vec[minIdx] = tmp;
}
}
void print(const std::vector<int>& v) {
for (const auto& i : v) {
std::cout << i << ' ';
}
std::cout << '\n';
}
int main() {
std::mt19937 prng(std::random_device{}());
std::uniform_int_distribution<int> dist(1, 1000);
std::vector<int> v;
for (int i = 0; i < 10; ++i) {
v.push_back(dist(prng));
}
print(v);
selection_sort(v);
print(v);
}
I opted not to give your code the 'light touch' treatment because than I would have done your homework for you, and that's just not something I do. However, the logic shown should still be able to guide you toward a working solution.

A question about dice probability and 2D array

Find out the probability of different total values when several unbiased dices were thrown at the same time. The program makes use of various techniques including basic I/O, arithmetic, conditional control structures, loops and arrays.
Visit https://drive.google.com/file/d/1gf10Pi_ME2jpmMM4_Y62-gkZ3we_llyy/view?usp=sharing for the details of information.
I am using the 2d array to finish the work. However, it was not okay to go on as it outputted the problem of "out of the scope".
#include <iostream>
using namespace std;
int main()
{
//Initialise the variables
int number;
cout << "Input the number of dice(s): ";
cin >> number;
//Initialise 2d array and set number as the row
int face[20][20];
for (int i = 0; i < number; i++) {
cin >> face[i + 1][20];
}
//Initialise 2d array and set input value as the column
int value;
for (int i = 0; i < number; i++) {
//Consider the output statement of the number of faces for dice
switch (number + 1) {
case 1:
cout << "Input the number of the faces for the " << number + 1 << "st" << " dice: ";
break;
case 2:
cout << "Input the number of the faces for the " << number + 1 << "nd" << " dice: ";
break;
case 3:
cout << "Input the number of the faces for the " << number + 1 << "rd" << " dice: ";
break;
default:
cout << "Input the number of the faces for the " << number + 1 << "th" << " dice: ";
}
cin >> face[i][value];
}
//calculate the sum of the dice
int sum = 0;
for (int i = 0; i < number; i++) {
sum = sum + face[i][value];
}
//initialise the base value (max probability) of the dice
int base;
for (int i = 0; i < number; i++) {
base = base * face[i][value];
}
//Output statement
if (number < 10) {
for (int i = number; i < sum; i++) {
cout << "Probability of " << i << " = " << probability(i, base, face);
}
}
else {
for (int i = number; i < 10; i++) {
cout << "Probability of " << i << " = " << probability(i, base, face);
}
for (int i = 10; i < sum; i++) {
cout << "Probability of " << i << " = " << probability(i, base, face);
}
}
return 0;
}
//Calculating the probability
int probability(int number, int base, int face[20][20])
{
int probability = 0;
int rollresult = face[0][0];
while (rollresult == number) {
for (int i = 0; i < number; i++) {
for (int j = 0; j; j++) {
rollresult = face[i][j] + rollresult;
}
}
probability++;
}
return probability;
}
error messages:
In function 'int main()':
51:69: error: 'probability' was not declared in this scope
56:70: error: 'probability' was not declared in this scope
59:70: error: 'probability' was not declared in this scope
The problem is that you are trying to call the probability() function before you have declared it! You can keep the actual definition after main but you will then need to put a 'forward' declaration of it earlier on. Try inserting a declaration, immediately before 'main`, thus:
int probability(int number, int base, int face[20][20]);
int main() {
...

How do you correctly pass arrays with pointers to a function?

I have to dynamically allocate an array and pass it to a function to calculate odds of a weighted die being rolled. Whenever I run through my code the function doesn't remember the values added to my array and returns random values, what's wrong about the way I'm passing *weight into the roll function? I added print statements after adding weights in and the weight is entered fine up until it's passed to the function via pointer.
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;
int roll (int sides, double *weight) {
int total[sides + 1];
total[0] = 0;
for (int i = 1; i <= sides; i++) {
total[i] = total[i - 1] + weight[i];
}
int current = (rand() % total[sides + 1] - 1 + 1);
//cout << current << " ";
for (int i = 1; i <= sides; i++) { // 1 to weight 1,,,,, weight 1 to weight
2
if (current <= total [i] && current > total[i - 1]) {
current = i;
}
}
return current;
}
Function that is supposed to retrieve the random number rolled. ^
int main () {
int sides = 0;
int rolls = 0;
int answer = 0;
int currentRoll = 0;
bool done = false;
double* weight;
double totalWeight;
srand(time(NULL));
cout << "Dice Roll Menu: " << endl << "1. Specify an output file" << endl <<
"2. Enter sides and weight for a die" << endl << "3. Simulate a specified
number of rolls of the weighted die" << endl << "4. Exit" << endl;
while (done != true) {
cout << endl << "Enter a number that corresponds to you choice: ";
cin >> answer;
while (answer == 2) { //SIDES
cout << "Please enter the number of sides on the die (must be
greater than two): ";
cin >> sides;
if (sides < 2) {
cout << "Invalid input, try again." << endl;
}
else {
weight = new double[sides + 1];
for (int i = 0; i < sides + 1; i++) {
weight[i] = 0;
}
break;
}
}
while (answer == 2) {
totalWeight = 0;
for (int i = 1; i <= sides; i++) { //WEIGHT
cout << "Enter a weight for side " << i << ": ";
cin >> weight[i];
cout << "TEST: " << weight[i] << endl;
totalWeight = weight[i] + totalWeight;
if (weight[i] < 0) {
cout << "Invalid input. Try again.";
totalWeight -= weight[i];
i--;
}
}
break;
}
Loop that determines sides and weight and dynamically allocates the array. ^
while (answer == 3) {
cout << "Enter the amount of rolls you would like to perform: ";
cin >> rolls;
if (rolls < 0) {
cout << "Invalid input. Try again.";
}
else {
else if (totalWeight == 0) {
cout << "Please enter weights of the dice first!" << endl;
answer = 1;
}
else {
done = true;
break;
}
}
}
//ACTUAL CODE HERE
for (int i = 1; i <= rolls; i++) { //CALCULATES
currentRoll = roll(sides, &weight[i]);
cout << currentRoll << " ";
}
}
Perhaps many of the misunderstandings that dominate the comments have to do with simply using C++ (and yet without using std::containers).
My out-of-the-box idea (or just plain crazy) is that there really is no conflict between:
"I have to be able to complete this program using 'dynamically allocated arrays', sadly I am not allowed to use vectors
yet all concerned seemed to agree that this is a C++ class assignment.
So, we need think of a way to create an array dynamically (I consider this part easy, not sure why). We want something with compile time fixed size. The array must exist in dynamic memory. (And no std containers.)
The goal has also been stated more simply
I have to dynamically allocate an array and pass it to a function to
calculate odds of a ...
I propose the following. (This code compiles and runs. )
#include <iostream>
using std::cout, std::flush, std::endl;
// Step 1 - wrap an array inside a class
class Array_t
{
const int m_sz;
int64_t* m_arr;
public:
Array_t()
: m_sz(128)
, m_arr (new int64_t[m_sz]) // allocate array in dynamic memory
{
// init for easy sum ... -------------v
for (int j=0; j<m_sz; j+=1) m_arr[j] = 1; // easy sum
}
~Array_t() = default;
int64_t sum() {
int64_t retVal = 0;
for (int i=0; i<m_sz; i+=1)
retVal += m_arr[i]; // direct access to the data!
return retVal;
}
};
// If your C++ 'Hello World' has no class ... why bother?
// Step 2 - auto var the above
class DUMY999_t
{
public:
DUMY999_t() = default;
~DUMY999_t() = default;
int operator()(int argc, char* argv[]) { return exec(argc, argv); }
private:
int exec(int , char** )
{
// here is the array wrapped in a class, an automatic var!
// the array is dynamically allocated in the class (see ctor)
Array_t arr;
// ctor provides the compile time constant
// Step 3
// pass the array (in the class) to some function foo()
cout << "\n foo(arr) :" << foo(arr) << endl;
// Step 4 - can we solve the 'how pass' question?
// It should be obvious that foo is redundant ...
// the following is both more direct
// and object-oriented (a good thing)
// >>> put the function in the object that has the data <<<
cout << "\n arr.sum() :" << arr.sum() << endl;
// invoke an object method which has
// direct access to the data!
return 0;
}
// why pass the data to the function? (c-style?)
int64_t foo(Array_t& arr)
{
return arr.sum();
}
// why not install the function into the object? (c++?)
}; // class DUMY999_t
int main(int argc, char* argv[]) { return DUMY999_t()(argc, argv); }
Typical output:
foo(arr) :128
arr.sum() :128

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

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);
}