C 编程中的运算符优先级
我目前正在学习 C 编程(我的第一门编程语言)。 我对运算符的优先级有点困惑。 算术运算符的优先级如下。
*
/
%
+
-
这至少是我书中给出的。 我感到困惑的是,在理论考试中我该如何解决表达式? 我尝试用上面给出的顺序解决许多表达问题,但未能得到正确的答案。
给出以下定义:
int a = 10, b = 20, c;
我们如何解决这个表达式?
a + 4/6 * 6/2
这是我书中的一个例子。
I am currently learning C Programming ( my first programming language ).
I am a little bit confused with the operators precedence.
Arithmetic operators precedence are as follows.
*
/
%
+
-
This is what is given in my book at least.
What i am confused is about how do i go solving expressions when it comes to my theory exams ?
I tried solving many expressing with the order given above but fail to get a correct answer.
Given the following definitions:
int a = 10, b = 20, c;
How would we solve this expression?
a + 4/6 * 6/2
This is an example in my book.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请注意,当使用整数除法时,
4/6
的计算结果为0
。Note that
4/6
evaluates to0
as integer division is used./
和*
的优先级在 C 中是相同的,就像在数学中一样。问题是,在数学中以下表达式是等价的,而在 C 中它们可能不是:这些在 C 中不等价,因为 if
a
,b
,c
和d
是整数,/
运算符表示整数除法(它只产生结果的整数部分)。例如,
一般良好的编码实践是明确表达您的意图。特别是,当有疑问时,请加上括号。有时甚至当你不在的时候。
The precedence of
/
and*
is the same in C, just as it is in mathematics. The problem is that in mathematics the following expressions are equivalent, whereas in C they might not be:These aren't equivalent in C because if
a
,b
,c
, andd
are integers, the/
operator means integer division (it yields only the integral part of the result).For example,
A general good coding practice is being explicit about your intentions. In particular, parenthesize when in doubt. And sometimes even when you're not.
现实生活中一种安全的解决方案是始终使用括号 ( )
One safe real life solution is to always use parentheses ( )