c++将2d数组传递给函数
c++ passing 2d arrays to funcions
我知道我的代码还没有完成,但我并没有要求它完成。它应该输入3只猴子一周吃的食物和其他东西。但是我遇到了一个障碍。它给了我一个错误(错误:没有操作符"<<"匹配这些操作数),当我把cin放在poundsEaten函数。我没有正确传递数组这就是为什么它不能工作吗?谢谢你的帮助
#include <iomanip>
#include <iostream>
using namespace std;
//Global Constants
const int NUM_MONKEYS = 3;
const int DAYS = 7;
//Prototypes
void poundsEaten(const double[][DAYS],int, int);
void averageEaten();
void least();
void most();
int main()
{
//const int NUM_MONKEYS = 3;
//const int DAYS = 7;
double foodEaten[NUM_MONKEYS][DAYS]; //Array with 3 rows, 7 columns
poundsEaten(foodEaten, NUM_MONKEYS, DAYS);
system("pause");
return 0;
}
void poundsEaten(const double array[][DAYS], int rows, int cols)
{
for(int index = 0; index < rows; index++)
{
for(int count = 0; count < DAYS; count++)
{
cout << "Pounds of food eaten on day " << (index + 1);
cout << " by monkey " << (count + 1);
cin >> array[index][count];
// Here is where i get the error
}
}
}
您已经声明array
包含const double
s。它们是常数,所以你不能像写cin >> array[index][count];
那样写它们。只需将参数声明更改为:
double array[][DAYS]
也许您应该考虑何时以及为什么应该将变量声明为const
。
double (*array)[DAYS]
但是,您的代码被适当地编写以处理此问题(您将row
s的数量传递给函数)。
您声明:
const double array[][DAYS],
然而,在poundsEaten
函数中,你要求用户输入信息来填充array
,这意味着array
不是const,因此,错误。从参数中删除const
限定符,以便array
可以通过用户输入更改。
void poundsEaten(double array[][DAYS], int rows, int cols)
BTW:不要使用array
作为数组的变量名,请使用其他名称。同时,cols
不能在poundsEaten
函数中使用。
相关文章:
- 第 i 个元素返回 i 的函数数组
- 使用嵌套函数数组是个好主意吗?
- 正确实现类函数数组
- 试图引用已删除函数数组的相等运算符
- 如何在静态函数中使用成员函数数组
- 无法创建函数数组
- 构造函数数组
- 使用开关或定义函数数组 - 更快
- 编写一个函数,该函数将覆盖主函数数组中的值
- 可以像'funs[1]();'一样调用的函数数组
- std::AVX内部函数数组
- 如果数组大小未知,如何将函数数组作为参数传递
- 从函数数组中获取值
- 使用元编程在编译时初始化函数数组
- 将C函数数组转换为C++函数指针数组
- 复制构造函数 [数组] C++
- 添加函数数组并随机选择其中一个
- 指针到私有成员函数数组
- 可以单独声明函数数组的元素
- (c++)将main中的随机值保存到函数数组中