宏的奇怪行为C / C ++ [英] Strange behaviour of macros C/C++

查看:194
本文介绍了宏的奇怪行为C / C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用一些宏,并观察一些奇怪的行为。



我已将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,以度计:<度(PI) endl;
cout<< 45度,以rad:<弧度(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,以度为单位:2880
45度,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)


I'm using some macros, and observing some strange behaviour.

I've defined PI as a constant, and then used it in macros to convert degrees to radians and radians to degrees. Degrees to radians works fine, but radians to degrees does not:

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;

}

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

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?

解决方案

Macros are (relatively simple) textual substitutions.

Use parentheses in your definitions (both to enclose the macro itself and the macro arguments):

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

这篇关于宏的奇怪行为C / C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆