[英]Example of passing an empty array to a function, inputting values in that function and returning values
我應該在main函數中創建一個空數組,然后使用兩個單獨的函數來1.接受輸入到數組中,然后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;
}
您應該將num
傳遞給函數; num[7]
表示數組的第8個元素(超出數組的范圍),但不是數組本身。 更改為
inputFoodAmounts(num);
foodFunction(num);
順便說一句: for (int i = 1; i < 7; i++)
看起來很奇怪,因為它只將數組從第二個元素迭代到第七個元素。
#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]
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.