Hi, I'm currently dealing with an issue trying to write a program for homework. I need to take the input of multiple temperatures (up to 50), then find the average, the highest, and the lowest temperature. However, it keeps outputting garbage data for the average, as well as outputting what should be the doubles as integers. If anyone has any help, it would be greatly appreciated. My code:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <string>
#include <cstring>
#include <iomanip>
#include <cmath>
#include <fstream>
usingnamespace std;
float findAvgTemp(float[], int count); //function that finds the average of the temperatures
float findHighTemp(float[], int count); //function that finds the highest of the temperatures
float findLowTemp(float[], int count); //function that finds the lowest of the temperatures
int main()
{
int count;
double average, high, low;
//Input number of temperatures
cout << "Please input the number of temperatures to be read\n";
cin >> count;
float temp[50];
//Input temperatures
for(int i = 0; i < count; i++)
{
cout << "Input temperature " << i+1 << ":\n";
cin >> temp[i];
}
average = findAvgTemp(temp, count);
high = findHighTemp(temp, count);
low = findLowTemp(temp, count);
cout << endl;
cout << "The average temperature is " << average << endl;
cout << "The highest temperature is " << high << endl;
cout << "The lowest temperature is " << low << endl;
return 0;
}
float findAvgTemp(float temp[], int count)
{
double average;
int sum = 0;
for(int j = 1; j <= count; j++)
{
sum += temp[j];
}
average = (sum / count);
return average;
}
float findHighTemp(float temp[], int count)
{
double high;
for(int k = 0; k < count; k++)
{
if(temp[k] > high)
{
high = temp[k];
}
}
return high;
}
float findLowTemp(float temp[], int count)
{
double low;
low = temp[0];
for(int m = 1; m < sizeof(temp)/sizeof(temp[0]); m++)
{
if(temp[m] < low)
{
low = temp[m];
}
}
return low;
}
I second what ShiftLeft said! :D But if your project requires you to use an array and call another function(s), then do try to accomplish all 3 goals (min, max, and average) in one function with 1 loop.
In the code put in the topic there are a few things (other then line 56 that ShiftLeft pointed out). Your main() func should inform the user that the limit is 50, and right after reading in count should check the value. If it's <= 0, it should reprompt the user for entry (this should be in a loop), if its > 50, you either reprompt or just assign it to 50 and tell the user what was done, or prompt again (either one).
In your findLowTemp() func on line 80, "m" needs to be compared to count, not the old trick that attempts to deduce array size. That "trick" compiles and silently produces the WRONG result unless the array itself is in scope of the sizeof() operator, so I don't recommend using it. (Technically there is a way to pass an array to another function and have the array's size be passed as part of the type, but it's trickier and more advanced).