该代码应该使用2d数组来获取3只猴子在一周内食用的食物并找到平均值,一天食用最低,一天食用量最高。最少的功能应该输出一只猴子在一天内吃掉的最低值,包括猴子数量,吃掉的磅数和日数。与最高功能相同。但它没有正确计算,我不知道我是否做错了。当我运行它打印出“吃掉的最低量是第1天的猴子1是1”然后打印出2,3,4等我尝试将cout放在循环外但是然后计数未初始化
#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;
}
}
}
答案 0 :(得分:1)
来自least
功能:
if(monkey[index][count] > lowest)
lowest = monkey[index][count];
在比较中,我确定您的意思是<
,而不是>
。
您还应该保存索引并在循环后打印,这适用于least
和most
。