我正在学习 C++,并且正在做这个使用函数打印三角形面积的练习,但是当我尝试编译时出现错误“[Error] 'calcarea' was not declared in this scope”
#include<iostream>
#include<cstdlib>
using namespace std;
double farea;
main(){
float base, height;
cout<<"Enter base of triangle: "; cin>>base;
cout<<"Enter height of triangle: "; cin>>height;
cout<<endl;
farea = calcarea(base,height);
cout<<"The area of the triangle is: "<<farea;
system("pause>nul");
}
double calcarea(float ba, float he){
double area;
area = (ba*he)/2;
return area;
}
最佳答案
您的编译器从头到尾读取代码,当它第一次遇到一个符号时,在本例中为 calcarea
,它会检查该符号是否已声明。由于 calcarea
仅在 之后声明,编译器当时并不知道此符号,因此,它是错误的:calcarea 未在此范围内声明
如果您将函数移动到它第一次调用之前,这个错误将得到解决。解决这个问题的另一种方法是只在 main 之前声明函数,然后在 main 之后定义它,这意味着,你将把你的函数留在原处,但在 main 之前添加一行定义它:double calcarea(float ba , float 他);
main(){
float base, height;
cout<<"Enter base of triangle: "; cin>>base;
cout<<"Enter height of triangle: "; cin>>height;
cout<<endl;
farea = calcarea(base,height); // here your compiler must already know what is calcarea, either by moving the definition, or only adding declaration
cout<<"The area of the triangle is: "<<farea;
system("pause>nul");
}
关于c++ - 在 C++ 上编译错误,未在此范围内声明 calcarea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43870660/