gpt4 book ai didi

C++ 将二维数组传递给函数

转载 作者:行者123 更新时间:2023-11-28 05:32:40 25 4
gpt4 key购买 nike

了解要计算数组的平均值,我们需要在下面声明一个函数。逐行循环和读取。

double getAverage(int arr[], int size)
{
int i, sum = 0;
double avg;

for (i = 0; i < size; ++i){
sum += arr[i];
}

avg = double(sum) / size;
return avg;
}

之后我们会调用main的值。

#include <iostream>
using namespace std;

// function declaration:
double getAverage(int arr[], int size);

int main ()
{
// an int array with 5 elements.
int balance[5] = {1000, 2, 3, 17, 50};
double avg;

// pass pointer to the array as an argument.
avg = getAverage( balance, 5 ) ;

// output the returned value
cout << "Average value is: " << avg << endl;

return 0;
}

所以我的问题是,如果我想计算行*列的平均值怎么办?我要宣布这样的事情吗?假设行和列的大小是 arr[3][6]

double getAverage(int arr[][6], int noOfrows, int noOfcol)
{
float sum=0, average;

for (int i = 0 ; i < noOfrows ; i++) {
for (int j = 0; j<noOfcol; j++) {
sum = sum + arr[i][j];
}
}
average = (float)sum / (float)(noOfcol*noOfrows);
cout << " " << average;

return average;
}

这是我的代码

int main()
{
int sales[3][6] = {{1000, 800, 780, 450, 600, 1200},
{800, 900, 500, 760, 890, 1000},
{450, 560, 570, 890, 600, 1100}};

int avg;

int choice;//menu choice

const int computeAverage_choice = 1,
computeTotal_choice = 2,
listMaxMin_choice = 3,
Exit_choice = 4;

do
{
//displayMenu(); // Show Welcome screen
choice = displayMenu();
while (choice < 1 || choice > 4)
{
cout << "Please enter a valid menu choice: " ;
cin >> choice;
}

//If user does not want to quit, proceed.
if (choice != Exit_choice)
{

switch (choice)
{
case computeAverage_choice:
avg = computeAverage(sales, 3, 6);
cout<<"The averge:" << avg;

break;

case computeTotal_choice:
//reserves
break;

case listMaxMin_choice:
//reserves
break;
}
}
} while (choice != Exit_choice);
return 0;
}

最佳答案

如果您的函数声明如下:double getAverage(int arr[][6], int noOfrows, int noOfcol) 但是您正在尝试调用它使用 avg = getAverage( balance, 5 ) ; [只有 2 个参数] 你的编译器应该返回一个错误。

只需将调用调整为 avg = getAverage( balance, 5 */num or rows*/, 6 */num of cols*/) ;

#include <iostream>
using namespace std;

double getAverage(int arr[][6], int noOfrows, int noOfcol)
{
float sum=0, average;

for (int i = 0 ; i < noOfrows ; i++) {
for (int j = 0; j<noOfcol; j++) {

sum = sum + arr[i][j];

}
}
average = (float)sum / (float)(noOfcol*noOfrows);
cout << " " << average;

return average;
}


int main()
{
int a[2][6] = {{1,2,3,4,5,6},{2,3,4,5,6,7}};
getAverage(a, 2, 6); // OK
getAverage( a, 5 ) ; // compile error
return 0;
}

关于C++ 将二维数组传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39072099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com