问题
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