我正在使用一些宏,并观察一些奇怪的行为。宏的奇怪行为C/C++
我已经将PI定义为常量,然后在宏中使用它将度数转换为弧度和弧度度。为弧度工作正常,但弧度度不:当我编译和运行,我得到下面的输出
#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;
}
:
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
好像
piTest.cpp我的常数PI在分子中起作用,但不是分母。我在C中观察到相同的行为。我正在运行gcc版本4.6.3
任何人都可以解释为什么我会得到这种行为吗?
请注意,对于'',您应该有'M_PI'这是一个字面常量。每次使用π时,你的代码实际上会调用'atan',这会使事情减慢很多。 –
Potatoswatter
'#define PI 3.14159265359' –
我在这里看不到gcc特有的东西。 – curiousguy