首页 > 解决方案 > 在函数 C++ 中返回数组的问题

问题描述

我对函数中的返回数组有疑问。编译器说:

main.cpp:在函数'int main()'中:main.cpp:52:13:错误:']'标记之前的预期主表达式 main.cpp:在函数'double Area(Trapec *,int)'中:main .cpp:65:12: 错误:']' 标记返回 p[] 之前的预期主表达式;

那是我的代码:

#include <iostream>
using namespace std;

struct Trapec
{
    double a=0;
    double b=0;
    double h=0;
};

double Area(Trapec);   

int main()
{
    int br;
    cout<<"Vuvedete broq na trapecite : ";
    cin>>br;
    // double S=0,min=0;
    //  double areas[50];
    Trapec p[50];
    for(int i=0;i<=br;i++){
        cout<<"Vuvedete a : ";
        cin>>p[i].a;
        cout<<"Vuvedete b : ";
        cin >>p[i].b;
        cout<<"Vuvedete h: ";
        cin>>p[i].h;
    }

    Area(p[]);

    return 0;
}

double Area(Trapec p[], int br)
{
    double S=0;
    double areas[50];
    for(int i=0;i<=br;i++){
        S=p[i].a + p[i].b + p[i].h;
        areas[i] = S;
    }
    return p[];
}

标签: c++arraysfunction

解决方案


您的代码中有几个问题:

  1. 你的函数声明和定义函数是不同的double Area(Trapec);double Area(Trapec p[], int br)是两个不同的函数。

  2. 循环结束条件错误(for(int i=0;i<=br;i++)),在这种情况下,它将比您输入的迭代次数多 +1 次,必须是for(int i=0;i<br;i++)i<br而不是i<=br

  3. 你的参数p( double Area(Trapec p[], int br)) 接受数组,编译器也接受它作为指针,所以不需要返回值,p 将改变传递数组的所有数据,将代码更改Area(...)为:

    void Area(Trapec p[], int br) { double S=0; double areas[50]; for(int i=0; i<=br ;i++) { S=p[i].a + p[i].b + p[i].h; areas[i] = S; } }

  4. pass 参数是错误的,不能传递 like Area(p[]);,必须有第二个参数br。您需要通过简单的Area(p,br);.

所以最后你的代码看起来像:

struct Trapec
{
    double a=0;
    double b=0;
    double h=0;
};

void Area(Trapec p[], int br);

int main()
{
    int br;
    cout<<"Vuvedete broq na trapecite : ";
    cin>>br;

    Trapec p[50];
    for(int i=0;i<br;i++){
        cout<<"Vuvedete a : ";
        cin>>p[i].a;
        cout<<"Vuvedete b : ";
        cin >>p[i].b;
        cout<<"Vuvedete h: ";
        cin>>p[i].h;
    }

    Area(p, br);

    return 0;
}

void Area(Trapec p[], int br)
{
    double S=0;
    double areas[50];
    for(int i=0; i<=br ;i++)
    {
        S=p[i].a + p[i].b + p[i].h;
        areas[i] = S;
    }
}

当输入测试数据输出如下所示:

Vuvedete broq na trapecite : 2
Vuvedete a : 1
Vuvedete b : 1
Vuvedete h: 1
Vuvedete a : 2
Vuvedete b : 2
Vuvedete h: 2
Program ended with exit code: 0

推荐阅读