[RESOLVED] I am getting weird out put when i run my program. Is there any way to fix this?
For my out put I am getting:
average = -171798688.00 (incorrect)
lowest = -858993472.00 (incorrect)
highest = 91.00 (correct)
Code:
#include <iostream>
#include <iomanip>
using namespace std;
// This program calculates the average of the inputed temperatures and finds the highest and lowest
// Jose Velazquez
int main()
{
int numOfTemp;
int temp[50];
int pos;
float findAverage(int[], float);
float findLowest(int[], float);
float findHighest(int[], float);
cout << "Please input the number of temperatures to be read (no more than 50)" << endl;
cin >> numOfTemp;
for (pos = 1; pos <= numOfTemp; pos++)
{
cout << "Input temperature " << pos << ":" << endl;
cin >> temp[pos];
}
cout << fixed << setprecision(2);
cout << "The average temperature is " << findAverage(temp, numOfTemp) << endl;
cout << "The lowest temperature is " << findLowest(temp, numOfTemp) << endl;
cout << "The highest temperature is " << findHighest(temp, numOfTemp) << endl;//calls function
system("pause");
return 0;
}
float findAverage(int temp[], float num)
{
float sum = 0;
for (int i = 0; i < num; i++)
{
sum = sum + temp[i];
return (sum / num); // calculates the average
}
}
float findLowest(int temp[], float num)
{
float lowest;
lowest = temp[0]; // make first element the lowest price
for (int count = 1; count < num; count++)
if (lowest > temp[count])
lowest = temp[count];
return lowest;
}
// This function returns the highest price in the array
float findHighest(int temp[], float num)
{
float highest;
highest = temp[0]; // make first element the highest price
for (int count = 1; count < num; count++)
if (highest < temp[count])
highest = temp[count];
return highest;
}
Re: I am getting weird out put when i run my program. Is there any way to fix this?
Two issues I see.
You're inputting temperatures into temp starting at index 1, yet you're doing your calculations starting on index 0.
Check out the position of your return statement in findAverage.
Re: I am getting weird out put when i run my program. Is there any way to fix this?
In c/c++ array indices start at 0. So for
The beginning element is 0 and the ending element is 49. ie
Code:
int first = temp[0];
int last = temp[49].