Closed 。这个问题需要细节或清晰度 /help/closed-questions 。目前不接受答案。
我正在尝试使用旧教科书自学 C++,非常感谢您的意见。我可以在线找到该程序的工作代码,但我想让我的代码在尝试完全不同的方法之前工作。
我需要编写一个程序,使用 3x7 二维数组来保存 3 只猴子一周的每日食物消耗量。
我需要输出平均每日总食物消耗量、任何猴子每周的最少食物消耗量以及任何猴子的每周最大食物消耗量。
到目前为止,一切正常,除了我的 getLeast 函数,它的作用就像听起来一样 - 获得猴子中每周食物消耗最少的函数。然而,它输出零,而我的 getMost 函数似乎工作正常。
此外,我欢迎任何可以就如何改进或简化我的代码提供建议的评论。谢谢阅读!
这是我的代码:
#include<iostream>
using namespace std;
const int numROWS = 3;
const int numCOLS = 7;
void getData(int array[][numCOLS], int);
double getAverage(int array[][numCOLS], int);
int getRowSum(int array[][numCOLS], int);
double getAverage(int array[][numCOLS], int);
int getLeast(int, int, int);
int getMost(int, int, int);
int main()
{
int monkeys[numROWS][numCOLS];
int monkey1 = 0, monkey2 = 1, monkey3 = 2, monk1Tot, monk2Tot, monk3Tot, most, least;
getData(monkeys,numROWS);
monk1Tot = getRowSum(monkeys, monkey1);
monk2Tot = getRowSum(monkeys, monkey2);
monk3Tot = getRowSum(monkeys, monkey3);
least = getLeast(monk1Tot, monk2Tot, monk3Tot);
most = getMost(monk1Tot, monk2Tot, monk3Tot);
cout << "The average daily food consumption by the monkeys was " << getAverage(monkeys, numROWS) << ". \n";
cout << "The least amount of food consumed within the week by a single monkey was " <<least << ". \n";
cout << "The greatest amount of food consumed within the week by a single monkey was " << most << ". \n";
}
void getData(int monkeys[][numCOLS],int numROWS)
{
for (int rows = 0; rows < numROWS; rows++)
{
cout << "Monkey " << (rows + 1) << "\n";
for (int cols = 0; cols < numCOLS; cols++)
{
cout << " Day " << (cols + 1) << ": ";
cin >> monkeys[rows][cols];
while (monkeys[rows][cols] < 0)
{
cout << "ERROR: Please enter a positive number: ";
cin >> monkeys[rows][cols];
}
}
cout << endl;
}
}
int getRowSum(int monkeys[][numCOLS], int monkeyNum)
{
int total = 0;
for (int rows = 0; rows < monkeyNum; rows++)
{
for (int cols = 0; cols < numCOLS;cols++)
total += monkeys[rows][cols];
}
return total;
}
double getAverage(int monkeys[][numCOLS], int numROWS)
{
double total = 0;
for (int cols = 0; cols < numCOLS; cols++)
{
for (int rows = 0; rows < numROWS; rows++)
total += monkeys[rows][cols];
}
return (total/(numCOLS));
}
int getMost(int monkey1, int monkey2, int monkey3)
{
int array[3]{monkey1, monkey2, monkey3};
int max = array[0];
for (int count = 0; count < 3; count++)
{
if (array[count] > max)
{
max = array[count];
}
}
return max;
}
int getLeast(int monkey1, int monkey2, int monkey3)
{
int array[3]{monkey1, monkey2, monkey3};
int least = array[0];
for (int count = 0; count < 3; count++)
{
if (array[count] < least)
{
least = array[count];
}
}
return least;
}