c++ - 在函数 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[];
}
解决方案
您的代码中有几个问题:
你的函数声明和定义函数是不同的
double Area(Trapec);
,double Area(Trapec p[], int br)
是两个不同的函数。循环结束条件错误(
for(int i=0;i<=br;i++)
),在这种情况下,它将比您输入的迭代次数多 +1 次,必须是for(int i=0;i<br;i++)
,i<br
而不是i<=br
。你的参数
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; } }
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
推荐阅读
- python - Python阿拉伯语文本以从右到左的方向而不是从左到右的方向返回
- html - 将文本放置在所需位置
- vb.net - 从 CSV VB.net 中搜索数组的功能
- python - 参数化数据框的列
- ios - Swift 5 协调后台任务
- google-apps-script - 将一列中的值与另一列中的逗号分隔值匹配并返回匹配的值
- c# - 在 .NET 服务中设置和使用自定义事件日志的正确方法?
- postgresql - 如果我有一个查询,我在 timescaledb 中加入一个带有普通(非超)表的超表,我会从超表中获益吗
- laravel - 在资源集合中使用 whenLoaded 我得到了错误
- php - 为按钮提供批准和拒绝功能,并将其显示在 Laravel 的用户仪表板中