【发布时间】:2015-01-18 12:41:36
【问题描述】:
此函数未准确返回输入到数组中的最高值和最低值。我不确定我为程序输入了什么代码来执行此操作。该程序需要返回输入到数组中的所有元素的平均值(平均值部分可以正常工作),并在输入到数组中的所有值中找到最高值和最低值。请帮忙!
#include <iostream>
using namespace std;
float temptotal = 0;
float averagetemp = 0;
float temperatures[50];
float average(int);
void highest(int);
void lowest(int);
int main()
{
int 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;
}
average(days);
highest(days);
lowest(days);
}
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
}
averagetemp = temptotal / days;
cout << "The average temperature is: " << averagetemp << endl;
return averagetemp;
}
void highest(int days)
{
int count;
int highest;
highest = temperatures[50];
for (count = 1; count < days; count++)
{
if (temperatures[count] > highest)
highest = temperatures[count];
cout << "The highest temperature is: " << highest << endl;
}
}
void lowest(int days)
{
int count;
int lowest;
lowest = temperatures[50];
for (count = 1; count < days; count++)
{
if (temperatures[count] < lowest)
lowest = temperatures[count];
cout << "The lowest temperature is: " << lowest << endl;
}
}
【问题讨论】:
-
数组索引从 0 开始,而不是 1。
-
你可能想从
highest = temperatures[0];开始。使用temperatures[50]是未定义的。