Finding the subscript of an array in a function in c++ - 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.

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

I'm having trouble with my C++ program using arrays/functions

For my class, I am needing to write a program using arrays instead of individual variables that contain the score. Struggling with this chapter. I'll leave my code below. Any help would be greatly appreciated. Needing to find the sum between all of the scores entered, subtract the highest and lowest and then find the average.
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototypes
void getJudgeData(double, double);
double calcScore(double);
double findLowest(double);
double findHighest(double);
int main()
{
// Declare variables
const int SIZE = 7;
double scores[SIZE];
double sum;
for (int x = 0; x < SIZE; x++)
double getJudgeData(scores[x]);
return 0;
}
// Function getJudgeData
void getJudgeData(double &judgeScore, double scores[])
{
static int judge = 1;
cout << "Enter score " << judge << ": ";
cin >> judgeScore;
while (judgeScore < 0 || judgeScore > 10)
{
cout << "Invalid score, please enter a score between 0 and 10";
cout << "Enter score " << judge << ": ";
cin >> judgeScore;
}
judge++;
return;
}
// Function calcScore
double calcScore(double scores[])
{
double highest = findHighest(scores);
double lowest = findLowest(scores);
double result = 0;
for (int x = 0; x < 7; x++)
{
result += scores[x];
}
result - findHighest(scores) - findLowest(scores);
cout << fixed << showpoint << setprecision(2);
cout << "The average after the dropping the highest and lowest scores: " << result / 5 << endl;
return result;
}
// Function findLowest
double findLowest(double scores[])
{
double result = 10;
for (int x = 0; x < 7; x++)
{
if (scores[x] < result)
result = scores[x];
}
return result;
}
// Function findHighest
double findHighest(double scores[])
{
double result = 0;
for (int x = 0; x < 7; x++)
{
if (scores[x] > result)
result = scores[x];
}
return result;
}

Maximum and minimum values not printing in main () function

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

Using the 3rd parameter of a function

Can anyone help me figure out how to get the 3rd parameter of the getLowest/getHighest function to reference the names array that has the months of the year and display the names of the month when I call for it? What's supposed to happen with those functions is that they are supposed to be able to give the name of the month that corresponds with the lowest/highest amount in the array. I can't seem to get it down. That's the last thing I need for this code and I'm trying very hard to figure it out. Any help would be much appreciated. Thank you.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//Function prototypes
double getTotal(double [], int);
double getAverage(double [], int);
double getLowest(double [], int, int&);
double getHighest(double [], int, int&);
int main()
{
const int months = 12;
string names[months] = { "January", "February", "March", "April",
"May", "June", "July", "August",
"September", "October", "November", "December" };
double rainfall[months];
double total, average, maxRain, minRain;
int indexofLowest, indexofHighest;
//Input from using for the rainfall amounts
std::cout << "Please enter the amount of rainfall in inches, that fell in each month.\n";
std::cout << "Enter the amount of rainfall for " << names[0];
std::cin >> rainfall[0];
std::cout << "Enter the amount of rainfall for " << names[1];
std::cin >> rainfall[1];
std::cout << "Enter the amount of rainfall for " << names[2];
std::cin >> rainfall[2];
std::cout << "Enter the amount of rainfall for " << names[3];
std::cin >> rainfall[3];
std::cout << "Enter the amount of rainfall for " << names[4];
std::cin >> rainfall[4];
std::cout << "Enter the amount of rainfall for " << names[5];
std::cin >> rainfall[5];
std::cout << "Enter the amount of rainfall for " << names[6];
std::cin >> rainfall[6];
std::cout << "Enter the amount of rainfall for " << names[7];
std::cin >> rainfall[7];
std::cout << "Enter the amount of rainfall for " << names[8];
std::cin >> rainfall[8];
std::cout << "Enter the amount of rainfall for " << names[9];
std::cin >> rainfall[9];
std::cout << "Enter the amount of rainfall for " << names[10];
std::cin >> rainfall[10];
std::cout << "Enter the amount of rainfall for " << names[11];
std::cin >> rainfall[11];
//Get total
total = getTotal(rainfall, months);
//Get average
average = getAverage(rainfall, months);
//Get the max amount of rain
maxRain = getHighest(rainfall, months, indexofHighest);
//Get the min amount of rain
minRain = getLowest(rainfall, months, indexofLowest);
//Display the total, average, highest/lowest
std::cout << "The total amount of rain for the year is " << total << " inches.\n";
std::cout << "The average amount of rain monthly is " << average << " inches per month.\n";
std::cout << "The month that had the highest amount of rainfall is " << names[indexofHighest] << " with " << maxRain << " inches.\n";
std::cout << "The month that has the lowest amount of rainfall is " << names[indexofLowest] << " with " << minRain << " inches.\n";
return 0;
}
//Definition of function getTotal
double getTotal(double rainfall[], int months)
{
double total = 0;
for (int count = 0; count < months; count++)
{
total += rainfall[count];
}
return total;
}
//Definition of function getAverage
double getAverage(double rainfall[], int months)
{
double total = 0;
double average = 0.0;
for (int count = 0; count < months; count++)
{
total += rainfall[count];
average = total / months;
}
return average;
}
//Defintion of function getLowest
double getLowest(double rainfall[], int months, int indexofLowest)
{
int count;
double lowest;
lowest = rainfall[0];
for (count = 1; count < months; count++)
{
if (rainfall[count] < lowest)
lowest = rainfall[count];
}
return lowest;
}
//Definition of function getHighest
double getHighest(double rainfall[], int months, int indexofHighest)
{
int count;
double highest;
highest = rainfall[0];
for (count = 1; count < months; count++)
{
if (rainfall[0] > highest)
highest = rainfall[count];
}
return highest;
}
I tried your code. You have a few bugs. I guess you need to try harder in the future. Anyways here is a working solution with minimal changes to your existing code -
//Defintion of function getLowest
double getLowest(double rainfall[], int months, int & indexofLowest)
{
int count;
double lowest;
lowest = rainfall[0];
for (count = 1; count < months; count++)
{
if (rainfall[count] < lowest)
{
lowest = rainfall[count];
indexofLowest = count;
}
}
return lowest;
}
//Definition of function getHighest
double getHighest(double rainfall[], int months, int & indexofHighest)
{
int count;
double highest;
highest = rainfall[0];
for (count = 1; count < months; count++)
{
if (rainfall[count] > highest)
{
highest = rainfall[count];
indexofHighest = count;
}
}
return highest;
}
You have to set indexofLowest and indexofHighest in your functions (and match their prototype):
//Defintion of function getLowest
double getLowest(double rainfall[], int months, int& indexofLowest)
int count;
double lowest;
lowest = rainfall[0];
for (count = 1; count < months; count++)
{
if (rainfall[count] < lowest) {
lowest = rainfall[count];
indexofLowest = count;
}
}
return lowest;
}
//Definition of function getHighest
double getHighest(double rainfall[], int months, int& indexofHighest)
{
int count;
double highest;
highest = rainfall[0];
for (count = 1; count < months; count++)
{
if (rainfall[count] > highest) { //there was a bug here in your code: ... rainfall[0]
highest = rainfall[count];
indexofHeighest = count;
}
}
return highest;
}
you can also use a function to input data (and maybe add a little error checking):
//Input from using for the rainfall amounts
int readData(string monthNames[], double rain[], int n) {
int i;
std::cout << "Please enter the amount of rainfall in inches, that fell in each month.\n";
for ( i=0; i<n; i++) {
std::cout << "Enter the amount of rainfall for " << monthNames[i];
std::cin >> rain[i]; //check this value somehow!
}
return i;
}

Variable initialization in functions

The variable days will not carry over throughout the function. I get an error saying that days isn't initialized in the highest and lowest functions and I have no idea how to fix it. Here's the code that I have so far.
#include <iostream>
using namespace std;
float temptotal = 0;
float averagetemp = 0;
float temperatures[50];
float average();
void highest();
void lowest();
int main()
{
average();
highest();
lowest();
}
float average()
{
float days = 0;
cout << "Enter the number of days: ";
cin >> days;
if (days > 50)
{
cout << "You may only enter temperatures for 50 days." << endl;
return 0;
}
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
return temperatures[i];
}
averagetemp = temptotal / days;
cout << "The average temperature is: " << averagetemp << endl;
}
void highest()
{
float max = -9999999999999;
for (int i = 0; i < days; i++)
{
if (temperatures[i] > max)
max = temperatures[i];
cout << "The highest temperature is: " << max << endl;
}
}
void lowest()
{
float min = 9999999999999;
for (int i = 0; i < days; i++)
{
if (temperatures[i] < min)
min = temperatures[i];
cout << "The lowest temperature is: " << min << endl;
}
}
You need to pass days to highest() and lowest(). If it's a common parameter for all 3 functions, you could set its value in main(), and then pass it to them. And I think days should be an int from your usage of for loop, so:
int main()
{
int days = 0;
cout << "Enter the number of days: ";
cin >> days;
average(days);
highest(days);
lowest(days);
}
float average(int days)
{
... ...
}
void highest(int days)
{
... ...
}
void lowest(int days)
{
... ...
}