[英]Operators precedence in C Programming
I am currently learning C Programming ( my first programming language ). 我目前正在学习C编程(我的第一门编程语言)。 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. 这是我书中的一个例子。
The precedence of /
and *
is the same in C, just as it is in mathematics. /
和*
的优先级在C中相同,就像在数学中一样。 The problem is that in mathematics the following expressions are equivalent, whereas in C they might not be: 问题在于,在数学中,以下表达式是等效的,而在C中,它们可能不是:
(a/b) * (c/d)
(a/b*c) / d
These aren't equivalent in C because if a
, b
, c
, and d
are integers, the /
operator means integer division (it yields only the integral part of the result). 它们在C中不等效,因为如果
a
, b
, c
和d
是整数,则/
运算符表示整数除法(它仅得出结果的整数部分)。
For example, 例如,
(7/2)*(4/5); //yelds 0, because 4/5 == 0
(7/2*4)/5; //yields 2
A general good coding practice is being explicit about your intentions. 一般的良好编码习惯是明确说明您的意图。 In particular, parenthesize when in doubt.
如有疑问,请特别加上括号。 And sometimes even when you're not.
有时即使您不在。
a + 4/6 * 6/2
= 10 + 4/6 * 6/2
= 10 + 0*6/2
= 10 + 0/2
= 10
Note that 4/6
evaluates to 0
as integer division is used. 请注意,由于使用了整数除法,因此
4/6
计算为0
。
一种安全的实际解决方案是始终使用括号()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.