此函数不能正确返回输入到数组中的最高和最低值。我不确定我为此程序输入的代码。该程序需要返回输入到数组中的所有元素的平均值(平均值部分工作正常),并找到输入到数组中的所有值中的最高和最低值。请帮忙!
#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;
}
}
该功能
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];
//...
已经错误,因为元素temperatures[0]
不会被初始化。你必须写
float average(int days)
{
for (int i = 1; i <= days; i++)
{
cout << "Enter the temperature for day number " << i << ": ";
cin >> temperatures[i-1];
temptotal += temperatures[i-1];
//...
或者
float average(int days)
{
for (int i = 0; i < days; i++)
{
cout << "Enter the temperature for day number " << i + 1 << ": ";
cin >> temperatures[i];
temptotal += temperatures[i];
//...
功能highest
和lowest
也是错误的。例如,数组temperatures
没有索引为50的元素。此外,用户可以输入少于50天的天数。因此,此语句
highest = temperatures[50];
是错的。
可以像该函数定义那样编写函数
void highest( int days )
{
int highest = temperatures[0];
for ( int count = 1; count < days; count++ )
{
if ( highest < temperatures[count] ) highest = temperatures[count];
}
cout << "The highest temperature is: " << highest << endl;
}
考虑到acccount有标准算法std::max_element
,std::min_element
,std::minmax_element
在头部声明<algorithm>
可以使用,而不是你的功能。
例如,可以通过std::max_element
以下方式使用标准算法定义最高功能
#include <algorithm>
//...
void highest( int days )
{
cout << "The highest temperature is: "
<< *std::max_element( temperatures, temperatures + days )
<< endl;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句