Maximum and minimum values not printing in main () function - c++

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

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

Your C++ program must use functions to input the scores, compute the average, and find the index of the highest score

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

assigning a function's output to variables in other function C++

I wrote a code to manage a coffee machine,
I have a function findC that finds the cheapest capsule in the capsule array
a different function of mine findVP that is supposed to use the findC function's output as variables. however, when I pass the variables mp, ind = findC(prices_copy, quantities_copy, SIZE);
and print them it passes them as 0;
but the 2nd cout : cout << findC(prices_copy, quantities_copy, SIZE); prints the correct output.
why is this ? and how can I pass the output of the function to another
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
// Example program
#include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
#define SLEEVE 10
#define SIZE 10
#define N 5
#define BUDGET 70
//int CapsuleKind[10] = {"JOE","MAC","NES","jamaica","brazil","columbia","MOJO","CLUB","JHON","COF"};
float findMostExpensiveCapsule( float prices[], int size ) // 1
{
float max = prices[0];
int count = 0;
for(int i = 1; i < size; i++)
{
if (prices[i] > max)
{
max = prices[i];
}
}
cout << "The maximum price " << max << " is found on indexes: " ;
for (int i = 0; i < size; i++)
{
if (prices[i] == max)
{
cout << i << " ";
count++;
}
}
cout << endl;
cout << "The maximum number appears " << count << " times." << endl;
return max;
}
int findStrongestCapsuleInStock( int quantities[], int size, int sleeve ) // 2
{
return 0;
}
void SellCapsules( int quantities[], int Qty, int index) // 10
{
quantities[index] = quantities[index] - Qty;
cout << "SOLD " << Qty << " capsules to the Customer, the total now is: " << quantities[index] << endl;
}
float findC( float prices[],int quantities[], int size ) // 9
{
float min = 99999;
int count = 0;
float index=0;
//sort(prices, arr + n);
for(int i = 0; i < size; i++)
{
if (quantities[i] >= SLEEVE)
{
if(prices[i] < min){
min = prices[i];
index= i;
}
else continue;
}
}
cout <<"the minimum price is : " << min << " ---- the index is : " << index << endl;
return min, index;
}
void findCheapestSleeve( float prices[],int quantities[], int size )
{
float min = prices[0];
int count = 0;
int index=0;
for(int i = 0; i < size; i++)
{
if (prices[i] < min)
{
if(quantities[i] > SLEEVE){
min = prices[i];
index= i;
}
else continue;
}
}
cout <<"the minimum price is : " << min << " ---- the index is : " << index << endl;
}
void showAllCapsulesInStock( int quantities[], float prices[], int size, int sleeve) // 3
{
for (int i = 0; i < size; i++)
{
cout << "capsule kind: " << i << " ---- sleeves available : " << (quantities[i]/sleeve) << " ---- price(for 1 sleeve): " << (prices[i]*sleeve)<< endl;
}
}
float findVP( float prices[], int quantities[], int size, float nis, int sleeve ) //4
{
float mp=0;
float ind =0;
float prices_copy[size];
int quantities_copy[size];
for(int i=0; i<size; i++){
prices_copy[i] = prices[i];
quantities_copy[i] = quantities[i];
}
mp, ind = findC(prices_copy, quantities_copy, SIZE);
cout << "The lowest price sleeve is: " << mp * 10 << " --- the capsule kind is: " << ind <<endl;
cout << findC(prices_copy, quantities_copy, SIZE);
}
void findValueForMoneyPackage( float prices[], int quantities[], int size, float nis, int sleeve )
{
int sleeve_num[size];
float sleeve_price[size];
float min=0;
int index = 0;
int counter=0;
float quant = 0;
for (int i=0; i < size; i++)
{
sleeve_num[i] = (quantities[i]/sleeve);
sleeve_price[i] = (prices[i] * sleeve);
}
//min, quant = findCheapestSleeve(sleeve_price, quantities, 10);
cout << "the cheapest sleeve costs : " << min << " and its of kind :" << quant << endl;
}
void addMoreCapsules( int quantities[], int size ) // 5
{
char answer;
int plus;
for (int i = 0; i < size; i++)
{
cout << "do you want to add capsules to capsule kind " << i << "? (Y/N) " << endl;
cin >> answer;
if (answer == 'Y')
{
cout << "How many capsules do you want to add (inter a number) " << endl;
cin >> plus;
if (plus > 0)
{
quantities[i] = quantities[i] + plus;
cout << "Added " << plus << " capsules to the inventory, the total now is: " << quantities[i] << endl;
}
}
else
{
continue;
}
}
}
// Driver Code
int main()
{
bool flag = false;
int option;
float prices[] = { 1.2, 2.2, 2.5, 1.7, 2.2, 3, 2.8, 2.5, 2.9, 3.7 };
int quantities[] = { 14, 22, 25, 13, 22, 33, 50, 60, 33, 25 };
while (flag != true)
{
cout << "Please choose an option , has to be a number 1-6" << endl;
cin >> option;
if (option == 1)
{
findMostExpensiveCapsule(prices,SIZE);
}
else if ( option == 3)
{
showAllCapsulesInStock(quantities, prices, SIZE, 10);
}
else if (option == 4){
findVP(prices, quantities, SIZE, BUDGET, SLEEVE);
}
else if(option == 5){
addMoreCapsules(quantities,SIZE);
}
else if(option == 9){
findC(prices, quantities, SIZE);
}
else
{
flag = true;
}
}
cout << "GoodBye!" << endl;
return 0;
}
This
return min, index;
doesn't do what you think it does. You obviously think it's going to return two values. But actually it just returns index.
This
mp, ind = findC(prices_copy, quantities_copy, SIZE);
doesn't do what you think it does. You obviously think it's going to assign the two returned values from findC to the variables mp and ind. But actually it's going to return the single value returned by findC to the variable ind and ignore mp.
If you want to know precisely what these constructs do then look up the comma operator, but I guess the moral of the story is that just because you can get some plausible looking code to compile it doesn't mean that it's going to do what you expected it to do.
So the real question is how to return two values from a function in C++. There are actually several possible approaches. Here's a question that reviews some of them, Returning multiple values from a C++ function.

Finding the subscript of an array in a function in c++

I have this homework and i've completed this up to now. where i am stuck...
Basically i need to get the largest amount of rainfall and display it (which i already do have completed it) but also the number of the month.
This is where i am having an intense headache...
could you guys help me out with some code?
#include <iostream>
#include <iomanip>
using namespace std;
double yearlyRainAverage(double[], const int);
double smallestRainfall(double [], const int);
double largestRainfall(double [], const int);
int searchHighestMonth(double[], int);
int main() {
const int months = 12;
double inchesOfRain[months];
double sumOfAllMonths=0;
int maxMonthPosition = searchHighestMonth(inchesOfRain, months);
for (int count = 0; count < months; count++)
{
cout<<"Enter the rainfall (in inches) for month #"<< count + 1<<": ";
cin>>inchesOfRain[count];
sumOfAllMonths += inchesOfRain[count];
if(inchesOfRain[count] < 0){
cout <<"Rainfall must be 0 or more.\n";
cout<<"please re-enter: "<<endl;
cout<<"Enter the rainfall (in inches) for month #"<< count + 1<<": ";
cin>>inchesOfRain[count];
}
}
cout << fixed << showpoint << setprecision(2) << endl;
cout<<"the total rainfall for the year is "<<sumOfAllMonths<<" inches"<<endl;
cout<<"the average is "<<yearlyRainAverage(inchesOfRain, 12)<<" inches"<<endl;
// cout<<"The smallest amount of rainfall was: "<<smallestRainfall(inchesOfRain, 12)<<" inches ";
// cout<<"in month "<<(monthPosition+1)<<endl;
cout<<"The largest amount of rainfall was: "<<largestRainfall(inchesOfRain, 12)<<" inches ";
cout<<"in month "<<maxMonthPosition+1<<endl;
return 0;
}
double yearlyRainAverage(double inchesofrain[], const int months){
double sum=0;
for(int i=0;i<months; i++){
sum+=inchesofrain[i];
}
return sum/months;
}
double smallestRainfall(double inchesofrain[], const int months){
double smallest;
int i;
smallest=inchesofrain[0];
for(i=0; i < months; i++){
if(inchesofrain[i] < smallest){
smallest = inchesofrain[i];
}
}
return smallest;
}
double largestRainfall(double inchesofrain[], const int months){
double largest;
int i;
largest=inchesofrain[0];
for(i=0; i < months; i++){
if(inchesofrain[i] > largest){
largest = inchesofrain[i];
}
}
return largest;
}
Here is where i think is the issue. i think my logic is wrong. But, i am not sure.
int searchHighestMonth(double inchesofrain[], int value){
int max = 0;
for ( int i=1; i < value; ++i) {
if ( inchesofrain[max] < inchesofrain[i] ) {
max = i;
}
}
return max;
}
The problem is that you are searching for your largest rainfall before you have taken the input of your rainfall from the user.
Move this line:
int maxMonthPosition = searchHighestMonth(inchesOfRain, months);
After the input for loop.
I went ahead and tested all of your code again, redirecting stdin (cin) from an input string, which I find very helpful for testing so I don't have to keep inputting. here is my code:
#include <iostream>
#include <sstream>
#include <iomanip>
using namespace std;
double yearlyRainAverage(double[], const int);
double smallestRainfall(double [], const int);
double largestRainfall(double [], const int);
int searchHighestMonth(double inchesofrain[], int value) {
int max = 0;
for (int i = 1; i < value; ++i) {
if (inchesofrain[max] < inchesofrain[i]) {
max = i;
}
}
return max;
}
int main() {
//#define testing // comment this line out to use std::cin for input
#ifdef testing
// code to get stdin input from a local buffer
std::string input_string{"4 5 6 7 8 9 10 3 2 3 4 5"};
std::streambuf *orig = std::cin.rdbuf();
std::istringstream input(input_string);
std::cin.rdbuf(input.rdbuf());
#endif
const int months = 12;
double inchesOfRain[months];
double sumOfAllMonths = 0;
for (int count = 0; count < months; count++) {
cout << "Enter the rainfall (in inches) for month #" << count + 1 << ": " << std::endl;
cin >> inchesOfRain[count];
sumOfAllMonths += inchesOfRain[count];
while (inchesOfRain[count] < 0) {
cout << "Rainfall must be 0 or more.\n";
cout << "please re-enter: " << endl;
cout << "Enter the rainfall (in inches) for month #" << count + 1 << ": " << std::endl;
cin >> inchesOfRain[count];
}
}
int maxMonthPosition = searchHighestMonth(inchesOfRain, months);
cout << fixed << showpoint << setprecision(2) << endl;
cout << "the total rainfall for the year is " << sumOfAllMonths << " inches" << endl;
cout << "the average is " << yearlyRainAverage(inchesOfRain, months) << " inches" << endl;
// cout<<"The smallest amount of rainfall was: "<<smallestRainfall(inchesOfRain, 12)<<" inches ";
// cout<<"in month "<<(monthPosition+1)<<endl;
cout << "The largest amount of rainfall was: " << largestRainfall(inchesOfRain, 12) << " inches ";
cout << "in month " << maxMonthPosition + 1 << endl;
#ifdef testing
std::cin.rdbuf(orig);
#endif
return 0;
}
double yearlyRainAverage(double inchesofrain[], const int months) {
double sum = 0;
for (int i = 0; i < months; i++) {
sum += inchesofrain[i];
}
return sum / months;
}
double smallestRainfall(double inchesofrain[], const int months) {
double smallest;
int i;
smallest = inchesofrain[0];
for (i = 0; i < months; i++) {
if (inchesofrain[i] < smallest) {
smallest = inchesofrain[i];
}
}
return smallest;
}
double largestRainfall(double inchesofrain[], const int months) {
double largest;
int i;
largest = inchesofrain[0];
for (i = 0; i < months; i++) {
if (inchesofrain[i] > largest) {
largest = inchesofrain[i];
}
}
return largest;
}
Your searchHighestMonth() function is almost good. But its loop must start at 0 not 1, like in the rest of your code. Loop is from 0 to 11 if it is a full year with 12 months. Besides, it is more readable if you store the current maximum rain value in some variable.
int searchHighestMonth(double inchesofrain[], int monthcount){
double maxrain = -1.0;
int max = -1;
for ( int i=0; i < monthcount; ++i) {
if ( maxrain < inchesofrain[i] ) {
maxrain = inchesofrain[i];
max = i;
}
}
return max;
}
Side remark: In actual production code, you would probably want to use std::vector objects, which maintain their own size, rather than plain old C-style arrays.
Side remark: if you want to give your user a second chance to enter a proper non-negative rainfall value, you must do it before including that value into the sum.

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