2017-10-18 44 views
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; 
} 

回答

1

您應該通過num函數; num[7]表示數組的第8個元素(並且它超出了數組的邊界),但不是數組本身。將其更改爲

inputFoodAmounts(num); 
foodFunction(num); 

BTW:for (int i = 1; i < 7; i++)看起來奇怪,因爲它只遍歷從第二個元素的數組第7之一。

+0

謝謝。對不起,我只是想通過提示做一個快速的示例工作,而沒有實際發佈作業。現在我想我已經掌握了基礎知識。 –

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]

+0

當你將一個數組傳遞給一個函數時,你將它作爲一個指針傳遞 - 你在原代碼中做了什麼是'inputFoodAmounts(num [7])'你做的是傳遞存儲在數組第7個索引中的值在這種情況下,類型爲「int」。這可能是你得到錯誤的原因。希望這有助於:D –

相關問題