变量days
不会在整个函数中继承。我收到一条错误消息,指出days
和highest
函数中未初始化lowest
,我不知道如何修复它。这是我到目前为止的代码。
#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[i];
temptotal += temperatures[i];
return temperatures[i];
}
averagetemp = temptotal / days;
cout << "The average temperature is: " << averagetemp << endl;
}
void highest()
{
float max = -9999999999999;
for (int i = 0; i < days; i++)
{
if (temperatures[i] > max)
max = temperatures[i];
cout << "The highest temperature is: " << max << endl;
}
}
void lowest()
{
float min = 9999999999999;
for (int i = 0; i < days; i++)
{
if (temperatures[i] < min)
min = temperatures[i];
cout << "The lowest temperature is: " << min << endl;
}
}
答案 0 :(得分:1)
您需要将days
传递给highest()
和lowest()
。如果它是所有3个函数的通用参数,则可以在main()
中设置其值,然后将其传递给它们。我认为days
应该是您使用for循环的int
,所以:
int main()
{
int days = 0;
cout << "Enter the number of days: ";
cin >> days;
average(days);
highest(days);
lowest(days);
}
float average(int days)
{
... ...
}
void highest(int days)
{
... ...
}
void lowest(int days)
{
... ...
}