我正在学习C ++,我正在练习使用函数打印三角形区域的练习,但是当我尝试编译时出现错误“[Error]'calcarea'未在此范围内声明”
#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;
}
答案 0 :(得分:2)
编译器正在帮助您。在您致电calcarea
时,它尚未被宣布。移动它或在main
之前声明它。
答案 1 :(得分:2)
您的编译器从头到尾读取代码,当它第一次遇到符号时,在本例中为calcarea
,它会检查符号是否已声明。由于calcarea
仅在之后声明为,因此当时编译器不知道此符号,因此,它是按摩: calcarea未在此范围内声明
如果您要将函数移动到第一次调用之前,则会解决此错误。解决这个问题的另一种方法是仅在main之前声明函数,并在之后定义它,这意味着你将把函数保留在原来的位置,但在main之前添加一行定义它:double calcarea(float ba, float he);
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");
}