加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

宏C/C++的奇怪行为

发布时间:2020-12-16 10:43:53 所属栏目:百科 来源:网络整理
导读:我正在使用一些宏,并观察一些奇怪的行为. 我已经将PI定义为常量,然后在宏中将其用于将度数转换为弧度,将弧度转换为度数.弧度到弧度的工作正常,但弧度到度数不会: piTest.cpp: #include cmath#include iostreamusing namespace std;#define PI atan(1) * 4#
我正在使用一些宏,并观察一些奇怪的行为.

我已经将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;

}

当我编译并运行时,我得到以下输出:

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

似乎我的常数PI在分子中起作用,但不是分母.我在C中观察到相同的行为.我正在运行gcc版本4.6.3

任何人都可以解释为什么我会得到这种行为?

解决方法

宏是(相对简单的)文本替换.

在定义中使用括号(包括宏本身和宏参数):

#define PI (atan(1) * 4)
#define radians(deg)  ((deg) * PI / 180)
#define degrees(rad)  ((rad) * 180 / PI)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读