无法通过函数传递参数

时间:2016-12-11 06:50:15

标签: c++

使用monthAverage()函数的函数调用时遇到问题,因为我不知道要传递什么才能使它工作。

// Zachary Fernandez
// Term Project Part II
// TP21_rainfall_statisitcs.cpp

#include <iostream>
#include <cstdlib>
#include <iomanip>
using namespace std;

void userInput(double rainfall[]);
double totalRainfall(double rainfall[]);
double monthlyAverage(double sum);

int main()
{
    double rainfall[12];

    cout << "Please enter the rainfall of each month of the year\n";
    cout << "seperated by a space.\n";

    userInput(rainfall);

    totalRainfall(rainfall);

    monthlyAverage();

    system("pause");
    return 0;
}

void userInput(double rainfall[])
{
    for (int i = 0; i < 12; i++)
    {
        cin >> rainfall[i];
    }
}

double totalRainfall(double rainfall[])
{
    double sum = 0;

    for (int i = 0; i < 12; i++)
    {
        sum += rainfall[i];
    }

    cout << "The total amount of rainfall for the year is: ";
    cout << sum;
    cout << endl;

    return sum;
}

这个函数有问题因为函数调用不允许我传递任何东西。我也不知道要通过什么才能使它发挥作用。

double monthlyAverage(double sum)
{
    double average;

    average = (sum / 12);

    cout << "The average monthly rain fall is: ";
    cout << average;
    cout << endl;

    return average;
}

5 个答案:

答案 0 :(得分:0)

此函数需要一个双参数

 double monthlyAverage(double sum);

所以你必须传递一个double值才能工作。喜欢

monthlyAverage(100.5);

在你的情况下它看起来像这样

monthlyAverage(totalRainfall(rainfall));

答案 1 :(得分:0)

嗯,你声明它接受一个双倍,所以任何双重值都可以。我假设sum表示总降雨量,因此您可以将totalRainfall()函数的值存储在变量中,然后传递变量,或者执行类似

的操作
int average = monthlyAverage(totalRainfall(rainfall));

这将使用totalRainfall函数返回的值并将其传递给monthlyAverage,然后将结果存储到int average。

答案 2 :(得分:0)

由于您的totalRainfall方法原型是 - double totalRainfall(double rainfall[]),这意味着该函数返回double值,您可以将其传递给monthlyAverage函数。

double total = totalRainfall(rainfall);
double avg = monthlyAverage(total);

您可以将返回值存储在变量(示例中为avg)中,如上所示。

答案 3 :(得分:0)

我认为你需要这样的东西:

int main()
{
    double rainfall[12];

    cout << "Please enter the rainfall of each month of the year\n";
    cout << "seperated by a space.\n";

    userInput(rainfall);

    double total = totalRainfall(rainfall);

    double avg = monthlyAverage(total);

    cout << "Monthly Average:" << avg << endl;    

    system("pause");
    return 0;
}

答案 4 :(得分:0)

观察你的背景,这个练习(?)似乎建议你写

monthlyAverage(totalRainfall(rainfall));

为什么呢?您看到totalRainfall返回double,并传递给monthlyAverage以输出平均值。

顺便说一句,你的system("pause");不是很便携。 Say, Apple version is different

相关问题