該代碼應該使用2d數組來獲取一週內3只猴子吃掉的食物,並找出平均值,一天中最低食用量,一天中最高。最小函數應該輸出一隻猴子在一天內吃掉的最低食物,並且包括猴子數量,吃過磅數和日數。與最高功能一樣。但它沒有正確計算,我不知道我是否做了錯誤的功能。當我運行它它打印出「的最低量是食用猴子1第1天爲1」,則打印出2,3,4等。我試圖把COUT外循環但然後計數未啓用初始化C++二維數組到函數
#include <iomanip>
#include <iostream>
using namespace std;
//Global Constants
const int NUM_MONKEYS = 3; // 3 rows
const int DAYS = 7; // 7 columns
//Prototypes
void poundsEaten(double[][DAYS],int, int);
void averageEaten(double [][DAYS], int, int);
void least(double [][DAYS], int, int);
void most(double [][DAYS], int, int);
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);
averageEaten(foodEaten, NUM_MONKEYS, DAYS);
least(foodEaten, NUM_MONKEYS, DAYS);
most(foodEaten, NUM_MONKEYS, DAYS);
system("pause");
return 0;
}
void poundsEaten(double monkey[][DAYS], int rows, int cols)
{
for(int index = 0; index < rows; index++)
{
for(int count = 0; count < cols; count++)
{
cout << "Pounds of food eaten on day " << (count + 1);
cout << " by monkey " << (index + 1) << ": ";
cin >> monkey[index][count];
}
}
}
void averageEaten(double monkey[][DAYS], int rows, int cols)
{
for(int count = 0; count < cols; count++)
{
double total = 0;
double average;
for(int index = 0; index < rows; index++)
{
total += monkey[index][count];
average = total/rows;
}
cout << "The average food eaten on day " << (count + 1)
<<" is " << average << endl;
}
}
void least(double monkey[][DAYS], int rows, int cols)
{
double lowest = monkey[NUM_MONKEYS][DAYS];
for(int index = 0; index < rows; index++)
{
for(int count = 0; count < cols; count++)
{
if(monkey[index][count] > lowest)
lowest = monkey[index][count];
cout << "The lowest amount of food eaten was monkey number
<< " " << (index + 1)
<< " On day " << (count + 1) << " was " << lowest;
}
}
}
void most(double monkey[][DAYS], int rows, int cols)
{
double highest = monkey[NUM_MONKEYS][DAYS];
for(int index = 0; index < rows; index++)
{
for(int count = 0; count < cols; count++)
{
if(monkey[index][count] > highest)
highest = monkey[index][count];
cout << "The highest amount of food eaten was monkey number"
<< (index + 1) << " on day " << (count + 1) << " was "
<< highest;
}
}
}
Yogi Berra:[「這就像deja'vu再次。」](http://stackoverflow.com/questions/15908496/c-passing-2d-arrays-to-funcions) – WhozCraig 2013-04-09 19:27:01
@WhozCraig和? – user1807815 2013-04-09 19:29:32
和...請參閱Joachim的答案(調試器和2分鐘會告訴你的答案)。他是對的。 – WhozCraig 2013-04-09 19:34:05