我需要此函数来打印输入到数组中的所有值的最大值,最小值和平均值。我遇到的问题是程序只打印出为阵列输入的最后一个值。防爆。如果我输入43,78和23,它只会打印23的平均值,最大值和最小值。得到这个输出我做错了什么?
#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[50];
}
temptotal += temperatures[50];
averagetemp = (temptotal / days);
cout << "The average temperature is: " << averagetemp << endl;
return temperatures[50];
}
void highest()
{
float max = -9999999999999;
if (temperatures[50] > max)
max = temperatures[50];
cout << "The highest temperature is: " << max << endl;
}
void lowest()
{
float min = 9999999999999;
if (temperatures[50] < min)
min = temperatures[50];
cout << "The lowest temperature is: " << min << endl;
}
答案 0 :(得分:0)
您将所有输入存储在数组的第50个元素中。
因此,最后一个会覆盖所有其他人。
这应该适用于平均。
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
}
average = temptotal / days ;
这应该适用于最大
float max = -9999999999999;
for( int i = 0 ; i < days ; i++ )
{
if (temperatures[i] > max)
max = temperatures[i];
}
cout << max;
并为min做类似的事情。