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

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

问题描述

我正在使用一些宏,并观察到一些奇怪的行为.

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

我将 PI 定义为一个常数,然后在宏中使用它来将度数转换为弧度,将弧度转换为度数.度数到弧度可以正常工作,但弧度到度数不能:

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:

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

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

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天全站免登陆