【发布时间】:2013-10-29 11:34:56
【问题描述】:
所以我无法从主函数(包含您输入的变量的数组)调用数据,并且不知道如何将其传递给 float getTotal 函数。这是我的代码:
#include <iostream> #include <iomanip> using namespace std; float getTotal(float [], int ) { double total = 0; for (int i=1; i<ARRAYSIZE; i++) { total += inputs[i]; } cout << "The total rainfall for the year is " << total << "inches." << endl; return total; } float getAverage(float [], int) { //code goes here } int main() { const int ARRAYSIZE = 13; int inputs[ARRAYSIZE], i=1; do { cout << "Enter the rainfall (in inches) for month #" << i << ": "; cin >> inputs[i]; if ( inputs[i] < 0 ) { cout << "Please enter a non-negative number for rainfall in month " << i << " :"; cin >> inputs[i]; } i++; } while (i < 13); float getTotal(float inputs[], int ARRAYSIZE); float getAverage(float inputs[], int ARRAYSIZE); }
所以我想从 main 调用数组数据并计算 getTotal 部分中的总数。我尝试了各种方法,都没有奏效。
【问题讨论】:
-
您遇到了哪些问题,在
main中填充数组,或将数组传递给函数? -
如果可能,请使用
std::vector而不是数组。现在,您尝试在getTotal中使用ARRAYSIZE,但它是main的本地对象,因此在getTotal中不可见。您还想为参数命名,以便可以在getTotal中访问它们。 -
@上面我在将数组传递给函数时遇到问题,所以我可以在getTotal函数中计算总数@Jeffry,你能给我一个例子吗?
标签: c++ arrays function methods