0

我刚刚开始学习 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; 
}
4

3 回答 3

2

问题比较简单。见下文。

#define pi 3.1415926535897932384626433832795 
int main() 
{
    // Create three float variable values: r, pi, area 
    float r, pi, area; 
...

请注意,您对pi. 这会将声明中的变量名称替换pi为 text 3.1415926535897932384626433832795。这会导致此处看到的错误:

错误:数字常量之前的预期不合格 id

现在,由于这导致对该语句的解析失败,因此area永远不会被声明(因为它是 after pi)。结果,您还会收到以下错误:

错误:“区域”未在此范围内声明

请注意,您实际上也既不分配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;
}
于 2012-09-02T00:32:45.243 回答
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;
}
于 2012-09-27T19:15:21.093 回答
0

对于初学者,您实际上从未将任何内容分配给“区域”,因此它仍然未定义(实际上包含一个随机数)。尝试area = r * r * pi;在最后一个 cout 之前添加该行。您还想float pi从变量列表中删除 ,因为它与#define pi顶部的 冲突。稍后,当您了解相关信息时,#include <math>可能会在内部找到一个M_PI常数,这样您就不必自己动手了。

于 2012-09-02T00:37:16.120 回答