c++ 2d数组到函数

c++ 2d arrays to funcions

本文关键字:函数 数组 2d c++      更新时间:2023-10-16

代码应该使用2d数组来获取3只猴子在一周内吃的食物,并找到平均值,一天内吃的最少,一天内吃的最多。最小函数应该输出一只猴子在一天内吃的最少的东西,包括猴子的数量、吃的磅数和天数。最高函数也是一样。但是计算不正确,我不知道我是否做错了函数。当我运行它时,它打印出"第一天吃的最少的量是猴子1是1",然后打印出2、3、4等等。我试着把count放到循环外,但是count没有初始化

#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;
    }
}

}

来自least函数:

if(monkey[index][count] > lowest)
    lowest = monkey[index][count];

在比较中,我确定你指的是<而不是>

您还应该保存索引并在循环之后打印,leastmost都是如此。