2017-05-09 81 views
0

我正在学习C++,我正在做这个练习,它使用函数打印三角形的区域,但是当我尝试编译“错误]“calcarea”未在此范围内声明“在C++上编译错误,在此范围内没有声明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; 
} 

回答

2

你的编译器从头到尾读取代码,当它第一次遇到一个符号,在这种情况下,calcarea它检查符号是否被声明。由于calcarea只宣布后,编译器,在那个时候,不知道这个符号的,因此,它的按摩:油杉没有在此范围内

声明如果你移动功能是在第一次调用之前,这个错误将被解决。解决此问题的另一种方法,是前主只声明该函数,后定义它,这意味着,你会离开你的函数它在哪里,但加之前主要定义它的行: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"); 
} 
+1

感谢有效! – OsmaK

2

编译器正在帮助您。在您拨打电话calcarea时,尚未声明。在main之前移动它或声明它。