2017-10-18 18 views
1

私はmain関数で空の配列を作成し、次に2つの別々の関数を使って配列に入力を受け入れ、 2.配列の値を表示します。空の配列を関数に渡し、その関数に値を入力して値を返す例

ここで私が思いついたのは、「int」から「int *」[-fpermissive]への無効な変換の行に沿って変換エラーが発生しています。しかし、私たちのクラスは今から2週間後まではポインタに到達しません。これは来週の予定ですので、ポインタをまだ使用していないと仮定します。

#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); 

にそれを変更します。それが唯一の第七一つに第二の要素から配列を反復処理するのでfor (int i = 1; i < 7; i++)は奇妙に見えます。

+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 –

関連する問題