我刚刚开始学习c ++,并且正在尝试编写一个用于查找圆圈区域的程序。我编写了程序,每当我尝试编译它时,我得到2条错误消息。第一个是:
areaofcircle.cpp:9:14: error: expected unqualified-id before numeric constant
,第二个是:
areaofcircle.cpp:18:5: error: 'area' was not declared in this scope
我该怎么办?我会发布一张图片,但我是新用户,所以我不能。
#include <iostream>
using namespace std;
#define pi 3.1415926535897932384626433832795
int main()
{
// Create three float variable values: r, pi, area
float r, pi, area;
cout << "This program computes the area of a circle." << endl;
// Prompt user to enter the radius of the circle, read input value into variable r
cout << "Enter the radius of the circle " << endl;
cin >> r;
// Square r and then multiply by pi area = r * r * pi;
cout << "The area is " << area << "." << endl;
}
答案 0 :(得分:2)
问题相对简单。见下文。
#define pi 3.1415926535897932384626433832795 int main() { // Create three float variable values: r, pi, area float r, pi, area; ...
请注意,您使用pi
的宏扩展。这将使用文本pi
替换声明中的变量名3.1415926535897932384626433832795
。这会导致此处出现错误:
错误:数字常量
之前的预期unqualified-id
现在,由于这导致解析在该语句上失败,area
永远不会被声明(因为它在pi
之后)。结果,您还会收到以下错误:
错误:未在此范围内声明'area'
请注意,您实际上既没有分配pi
也不分配area
...您需要先执行此操作。
作为一般经验法则,不要将宏用于C ++中的常量。
#include <iostream>
#include <cmath>
int main() {
using std::cin;
using std::cout;
using std::endl;
using std::atan;
cout << "This program computes the area of a circle." << endl;
cout << "Enter the radius of the circle " << endl;
float r;
cin >> r;
float pi = acos(-1.0f);
float area = 2 * pi * r;
cout << "The area is " << area << '.' << endl;
return 0;
}
答案 1 :(得分:0)
对于初学者来说,你实际上从未向“区域”分配任何内容,因此它仍未定义(实际上包含一个随机数)。尝试在最后一个cout之前添加行area = r * r * pi;
。您还希望从变量列表中删除float pi
,因为它与顶部的#define pi
发生冲突。之后,当您了解#include <math>
时,可能会在内部找到M_PI
常量,这样您就不必自己动手了。
答案 2 :(得分:0)
修改后的代码构建并正常工作:
///--------------------------------------------------------------------------------------------------!
// file: Area.cpp
//
// summary: console program for SO
#include <iostream>
using namespace std;
const double PI = 3.1415926535897932384626433832795;
int main()
{
// Create three float variable values: r, pi, area
double r, area;
cout << "This program computes the area of a circle." << endl;
// Prompt user to enter the radius of the circle, read input value into variable r
cout << "Enter the radius of the circle " << endl;
cin >> r;
// Square r and then multiply by pi area = r * r * pi;
area = PI*r*r;
cout << "The area is " << area << "." << endl;
return 0;
}