此函数未准确返回输入到数组中的最高值和最低值。我不确定我为程序输入了什么代码来执行此操作。该程序需要返回输入到数组中的所有元素的平均值(平均部分可以正常工作),并找到输入到数组中的所有值中的最高值和最低值。请帮忙!
#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;
}
考虑到有标准算法std::max_element
, std::min_element
, std::minmax_element
在 header 中声明 <algorithm>
可以用来代替您的函数。
例如可以使用标准算法定义函数 highest std::max_element
以下方式
#include <algorithm>
//...
void highest( int days )
{
cout << "The highest temperature is: "
<< *std::max_element( temperatures, temperatures + days )
<< endl;
}
关于c++ - 函数不返回输入数组的最高值和最低值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27043233/