#define in C: what is happening [closed]

守給你的承諾、 提交于 2020-06-29 03:47:14

问题


Can someone explain what is happening at every step? I know the final output is 140.5, but I am unsure why that is. What is happening at each line that is resulting in 140.5?

#define PI 3.1
#define calcCircleArea(r) (PI * (r) * (r))
#define calcCylinderArea(r,h) (calcCircleArea(r) * h)
int main() {
    double i = calcCylinderArea(3.0,5.0 + 1); printf("%g", i);
}

回答1:


Step 0

calcCylinderArea(3.0,5.0+1)

Step 1

(calcCircleArea(3.0)*5.0+1)

notice that it is not (5.0+1).
Problem begins here.

Step 2

((PI*(3.0)*(3.0))*5.0+1)

Step 3

((3.1*(3.0)*(3.0))*5.0+1)



回答2:


calcCylinderArea(3.0,5.0 + 1) is evaluated as: calcCircleArea(3.0) * 5.0 + 1 which is evaluated as: PI * 3.0 * 3.0 * 5.0 + 1 which is 140.5

multiplication is done before addition

To fix the issue change the line to: calcCylinderArea(3.0,(5.0 + 1)) so that the addition is done first.



来源:https://stackoverflow.com/questions/61491522/define-in-c-what-is-happening

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!