rai*_*lin 3 c++ macros gcc pi c-preprocessor
我正在使用一些宏,并观察一些奇怪的行为.
我已经将PI定义为常量,然后在宏中将其用于将度数转换为弧度,将弧度转换为度数.弧度到弧度的工作正常,但弧度到度数不会:
piTest.cpp:
#include <cmath>
#include <iostream>
using namespace std;
#define PI atan(1) * 4
#define radians(deg) deg * PI / 180
#define degrees(rad) rad * 180 / PI
int main()
{
cout << "pi: " << PI << endl;
cout << "PI, in degrees: " << degrees(PI) << endl;
cout << "45 degrees, in rad: " << radians(45) << endl;
cout << "PI * 180 / PI: " << (PI * 180 / PI) << endl;
cout << "3.14159 * 180 / 3.14159: " << (3.14159 * 180 / 3.14159) << endl;
cout << "PI * 180 / 3.14159: " << (PI * 180 / 3.14159) << endl;
cout << "3.14159 * 180 / PI: " << (3.14159 * 180 / PI) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
When I compile and run, I get the following output:
pi: 3.14159
PI, in degrees: 2880
45 degrees, in rad: 0.785398
PI * 180 / PI: 2880
3.14159 * 180 / 3.14159: 180
PI * 180 / 3.14159: 180
3.14159 * 180 / PI: 2880
Run Code Online (Sandbox Code Playgroud)
It seems like my constant PI works in the numerator, but not the denominator. I've observed the same behaviour in C. I'm running gcc version 4.6.3
Can anyone explain why I'm getting this behaviour?
宏是(相对简单的)文本替换.
在定义中使用括号(包括宏本身和宏参数):
#define PI (atan(1) * 4)
#define radians(deg) ((deg) * PI / 180)
#define degrees(rad) ((rad) * 180 / PI)
Run Code Online (Sandbox Code Playgroud)
小智 5
首先,cmath
定义M_PI
,使用它.
其次,cpp宏进行文本替换.这意味着:
#define PI atan(1) * 4
a = 1 / PI;
Run Code Online (Sandbox Code Playgroud)
将变成这样:
a = 1 / atan(1) * 4;
Run Code Online (Sandbox Code Playgroud)
在c/c ++编译器有机会看到你的代码之前,它会将它视为等同于:
a = (1 / atan(1)) * 4;
Run Code Online (Sandbox Code Playgroud)
这不是你想要的.
您的定义应如下所示:
#define PI (atan(1) * 4)
Run Code Online (Sandbox Code Playgroud)
一切都应该没问题.
这不是真正奇怪的行为,而是c-preprocessor的良好记录行为.
您应该在网上搜索宏的其他陷阱.(提示:参数传递)
归档时间: |
|
查看次数: |
982 次 |
最近记录: |