我应该在main函数中创建一个空数组,然后使用两个单独的函数来接受数组中的输入,然后2.显示数组的值。
以下是我提出的内容,并且我在从“int”到“int *”[-fpermissive]的无效转换中遇到转换错误。但是,我们的课程从现在开始两周后才开始指示,这将在下周发布,所以我假设我们还没有使用指针。
#include <iostream>
#include <iomanip>
using namespace std;
int inputFoodAmounts(int[]);
int foodFunction(int[]);
int main()
{
int num[7];
cout << "Enter pounds of food";
inputFoodAmounts(num[7]);
foodFunction(num[7]);
return 0;
}
int inputFoodAmounts(int num[])
{
for (int i = 1; i < 7; i++)
{
cout << "Enter pounds of food";
cin >> num[i];
}
}
int foodFunction(int num[])
{
for (int j = 1; j < 7; j++)
{
cout << num[j];
}
return 0;
}
答案 0 :(得分:1)
您应该将num
传递给函数; num[7]
表示数组的第8个元素(并且它超出了数组的范围),但不是数组本身。将其更改为
inputFoodAmounts(num);
foodFunction(num);
BTW:for (int i = 1; i < 7; i++)
看起来很奇怪,因为它只是将数组从第二个元素迭代到第七个元素。
答案 1 :(得分:1)
#include <iostream>
#include <iomanip>
using namespace std;
void inputFoodAmounts(int[]); //made these two functions void you were not returning anything
void foodFunction(int[]);
int main()
{
int num[7];
inputFoodAmounts(num); //when passing arrays just send the name
foodFunction(num);
system("PAUSE");
return 0;
}
void inputFoodAmounts(int num[])
{
cout << "Please enter the weight of the food items: \n"; //a good practice is to always make your output readable i reorganized your outputs a bit
for (int i = 0; i < 7; i++) //careful: you wanted a size 7 array but you started index i at 1 and less than 7 so that will only give you
{ // 1, 2, 3, 4, 5, 6 -> so only 6
cout << "Food "<<i +1 <<": ";
cin >> num[i];
}
}
void foodFunction(int num[])
{
cout << "Here are the weight you entered: \n";
for (int j = 0; j < 7; j++)
{
cout << "Food "<<j+1<<": "<<num[j]<<" pounds\n";
}
}
我相信您收到了无效的类型错误,因为您传递了数组num[7]
。