c++ - 编译器错误 : 'area' not declared in this scope

标签 c++ compiler-errors

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

最佳答案

问题比较简单。见下文。

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

请注意,您对 pi 使用了宏扩展。这会将声明中的变量名 pi 替换为文本 3.1415926535897932384626433832795。这会导致此处出现的错误:

error: expected unqualified-id before numeric constant

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

error: 'area' was not declared in this scope

请注意,您实际上既没有分配 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;
}

关于c++ - 编译器错误 : 'area' not declared in this scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12232432/

相关文章:

c++ - 避免在头文件中包含私有(private)方法所需的内容

c++ - 如何解决我们必须向前和向后迭代的 Broken Necklace Problem

c++ - 有没有办法为函数创建预处理器宏?

c++ - 错误 'map' 未在此范围内声明

java - 编译器错误: cannot find symbol,符号: class JSPWriter,位置:类转换器

c++ - Boost 从 1.42 升级到 1.61

C++ int& operator[](string key) 函数使用链表

c++ - 在eventFilter触发之前发出对象的事件

java - 使用JAVA访问集合Genexus Item

时间:2018-01-08 标签:c++mexerror: invalid types ‘double[mwSize]’ for array subscript