坚持使用C ++函数和数组

时间:2012-11-08 01:02:02

标签: c++ visual-c++

#include <iostream>
using namespace std;

const int monkeys = 3;
const int weekdays = 7;
double monkeyWeek[monkeys][weekdays];
double largest;
double least;
double average;
int index;
int dayCount;
double amount;



double amountEaten(double[] [weekdays], int);
double mostEaten (double[] [weekdays],int);
double leastEaten (double[][weekdays], int);

int main(){
cout << "Ch 7-4 Monkey " << endl;
cout << "Created by Aaron Roberts" << endl;

double mostBananas (double[] [weekdays],int);
double leastBananas (double[][weekdays],int);
//double bananaAverage (double[][weekdays], int);



}


double amountEaten(double array[] [weekdays], int){
    cout << "Please enter the amount of food eaten per monkey per day." << endl;
double amount = array[0][0];
for (index = 0; index < monkeys; index++)
{
    for (dayCount = 0; dayCount < weekdays; dayCount++)
    {
    cout << endl <<"Please enter the amount of pounds eaten by     monkey"     
        <<(index +1)
            << endl << "for day " << (dayCount +1) << ": ";
        cin >> monkeyWeek[monkeys] [weekdays] ;
        if (monkeyWeek[monkeys] [weekdays] < 1)
            cout << endl <<"Must feed positive amount" << endl;
    }


}
}

double mostEaten( double array[] [weekdays], int size)
{
double largest = array[0][0];
for (int count = 0; count < size; count++)
{
    for (int col = 0; col < count; col++)
    {
        if (array[count][weekdays] > largest)
            largest = array[count][weekdays];
    }
}
return largest;
}

double leastEaten(double array[] [weekdays], int size)
{
double least = array[0][0];

for (int count = 0; count < size; count++)
{
for (int col = 0; col < size; col++);
{
if (array[count][weekdays] < least)
least = array[count][weekdays];
}
}
return least;
} 

这个项目需要使用二维数组来存储一周七天中每只猴子吃掉的食物的磅数。

创建一个函数,以获得每周猴子每周吃掉的磅数。 创建第二个函数以确定通过数组传递以计算所有资金的总量,然后在一天内吃掉平均值。 (有些人将此解释为对所有值求和,然后除以值的数量。其他人将此解释为将每天的值相加并计算当天的平均值。因此,将有7行输出,而不仅仅是一行。 )

创建第三个功能,以确定哪只猴子吃的食物量最少,以及哪一天。还输出那天猴子吃的数量。 创建第四个功能,以确定哪一只猴子在一天内吃了最多的食物。输出猴子数,吃掉的磅数和工作日。

我是c ++的新手并且卡住了,并不知道如何完成这个。感谢任何帮助,我真的很感激。

1 个答案:

答案 0 :(得分:1)

你继续这样做:

for (int count = 0; count < size; count++)
{
    for (int col = 0; col < count; col++)
    {
        if (array[count][weekdays] > largest)
            largest = array[count][weekdays];
    }
}

看到您正在使用weekdays索引数组。但该指数无效。它可能有点工作,但总会返回下一行的第一个元素(然后在最后一行有更明确的未定义行为)。

我很确定你打算在这里使用col代替weekdays

正如WhozCraig在评论中指出的那样,你可能也需要遍历整个weekdays范围。这是一个稍微修复过的循环:

for (int count = 0; count < size; count++)
{
    for (int col = 0; col < weekdays; col++)
    {
        if (array[count][col] > largest)
            largest = array[count][col];
    }
}

同样对于其他地方你也做过这个......