2017-05-09 47 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之前移動它或聲明它。