乘法和除法:C语言中的奇怪输出 [英] Multiplication and division: weird output in c
问题描述
我读到*
(乘法)比/
(除法)具有更高的优先级.因此,如果同时存在*
和/
的方程,则*
必须首先发生.
I read that *
(multiplication) has has higher presedence than /
(division). Thus if there is an equation with both *
and /
, then *
must take place first.
但是我看过一个程序,它输出一些奇怪的东西
But I've seen a program that output something strange
#include<stdio.h>
#define SQUARE(x) x*x
int main()
{
float s=10, u=30, t=2, a;
a = 2*(s-u*t)/SQUARE(t);
printf("Result = %f", a);
return 0;
}
运行此命令时,我以为输出为-25,但实际上为-100.
When running this, I thought that the output would be -25, but in fact it was -100.
当我寻找解释时
Step 2: a = 2*(s-u*t)/SQUARE(t); becomes,
// Here SQUARE(t) is replaced by macro to t*t
=> a = 2 * (10 - 30 * 2) / t * t;
=> a = 2 * (10 - 30 * 2) / 2 * 2;
=> a = 2 * (10 - 60) / 2 * 2;
=> a = 2 * (-50) / 2 * 2 ;
/*till here it's OK*/
/*why it divided -50 by 2 before multiplying 2*2 and -50*2 */
=> a = 2 * (-25) * 2 ;
=> a = (-50) * 2 ;
=> a = -100;
有人可以解释吗?
推荐答案
肢体偏执狂!您的宏应为:
Parenthesis paranoia! Your macro should be:
#define SQUARE(X) ((x)*(x))
否则,优先级规则和宏扩展会做一些奇怪的事情.您的宏:
Or else precedence rules and macro expansion will do weird things. Your macro:
100 / SQUARE(2)
将扩展为:
100 / 2*2
,它的意思是:
(100/2) * 2
是100,而不是25.
which is 100, not 25.
其他异常,而不是代码中的异常是,如果您尝试对表达式求平方:
Other anomaly, not in your code is if you try to square an expression:
SQUARE(2+2)
将扩展为
2+2*2+2
是8
,而不是预期的16
.
结论:在宏中写很多括号.到处都是.
Conclusion: in macros write a lot of parentheses. Everywhere.
这篇关于乘法和除法:C语言中的奇怪输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!