[英]compiling error on c++, calcarea was not declared in this scope
我正在學習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;
}
編譯器正在幫助您。 到目前為止,您尚未將其稱為calcarea
。 將其移動或在main
之前聲明。
您的編譯器從頭到尾讀取代碼,當它第一次遇到符號時(在這種情況下為calcarea
,它將檢查符號是否已聲明。 由於calcarea
僅在after之后聲明,因此當時的編譯器並不知道此符號,因此,它得到了提示: 在此范圍內未聲明calcarea
如果將函數移到第一次調用之前,它將得到解決。 解決此問題的另一種方法是,僅在main之前聲明函數,然后在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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.