首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >将空数组传递给函数、在该函数中输入值并返回值的示例

将空数组传递给函数、在该函数中输入值并返回值的示例
EN

Stack Overflow用户
提问于 2017-10-18 10:00:31
回答 2查看 223关注 0票数 1

我应该在main函数中创建一个空数组,然后使用两个单独的函数来1.接受数组的输入,然后2.显示数组的值。

这是我想出来的,我得到了从'int‘到'int*’-fpermissive的无效转换的转换错误。然而,我们的类直到两周后才开始使用指针,这是下周到期的,所以我假设我们还没有开始使用指针。

代码语言:javascript
运行
复制
#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;
}
EN

回答 2

Stack Overflow用户

发布于 2017-10-18 10:04:17

您应该将num传递给函数;num[7]表示数组的第8个元素(它超出了数组的界限),而不是数组本身。将其更改为

代码语言:javascript
运行
复制
inputFoodAmounts(num);
foodFunction(num);

顺便说一下:for (int i = 1; i < 7; i++)看起来很奇怪,因为它只迭代从第二个元素到第七个元素的数组。

票数 1
EN

Stack Overflow用户

发布于 2017-10-18 10:27:35

代码语言:javascript
运行
复制
#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]

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46801712

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档