函数中的变量初始化

时间:2014-11-20 02:09:16

标签: c++ function variables

变量days不会在整个函数中继承。我收到一条错误消息,指出dayshighest函数中未初始化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;
    }
}

1 个答案:

答案 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)
{
    ... ...
}