设为首页 加入收藏

TOP

5.1 Arithmetic Operators (2)
2013-10-07 15:25:31 来源: 作者: 【 】 浏览:50
Tags:5.1 Arithmetic Operators

The % operator is known as the “remainder” or the “modulus” operator. It computes the remainder of dividing the left-hand operand by the right-hand operand. This operator can be applied only to operands of the integral types: bool, char, short, int, long, and their associated unsigned types:

  1. int ival = 42;  
  2. double dval = 3.14;  
  3. ival % 12; // ok: returns 6  
  4. ival % dval; // error: floating point operand 

For both division (/) and modulus (%), when both operands are positive, the result is positive (or zero). If both operands are negative, the result of division is positive (or zero) and the result of modulus is negative (or zero). If only one operand is negative, then the value of the result is machine-dependent for both operators. The sign is also machine-dependent for modulus; the sign is negative (or zero) for division:

  1. 21 % 6; // ok: result is 3  
  2. 21 % 7; // ok: result is 0  
  3. -21 % -8; // ok: result is -5  
  4. 21 % -5; // machine-dependent: result is 1 or -4  
  5. 21 / 6; // ok: result is 3  
  6. 21 / 7; // ok: result is 3  
  7. -21 / -8; // ok: result is 2  
  8. 21 / -5; // machine-dependent: result -4 or -5 

When only one operand is negative, the sign and value of the result for the modulus operator can follow either the sign of the numerator or of the denominator. On a machine where modulus follows the sign of the numerator then the value of division truncates toward zero. If modulus matches the sign of the denominator, then the result of division truncates toward minus infinity.

根据定义,C++(www.cppentry.com) 的整数除法与取模运算满足:被除数= 商* 除数+ 余数。C++(www.cppentry.com) 语言的整数除法是“截断”的,即两个整数相除仍然得到整数。对于被除数和除数都是正数的情况一般不会有什么疑问;如果被除数或除数有一个是负数,现版的C++(www.cppentry.com) 标准留给实现去决定余数的正负号和商的截断方向。如果余数的符号与被除数相同,那么商是向零截断;如果余数的符号与除数相同,那么商是向负无穷截断。

注意:新版的C++(www.cppentry.com) 标准要求余数的正负号和被除数相同,并且商向零取整,即 21/5= 4 且 21%5= 1。实际的硬件也都是按这个规则来实现整数除法的。

EXERCISES SECTION 5.1

Exercise 5.1: Parenthesize the following expression to indicate how it is eva luated. Test your answer by compiling the expression and printing its result.

  1. 12 / 3 * 4 + 5 * 15 + 24 % 4 / 2 

Exercise 5.2: Determine the result of the following expressions and indicate which results, if any, are machine-dependent.

  1. -30 * 3 + 21 / 5  
  2. -30 + 3 * 21 / 5  
  3. 30 / 3 * 21 % 5  
  4. -30 / 3 * 21 % 4 

Exercise 5.3: Write an expression to determine whether an int value is even or odd.

Exercise 5.4: Define the term overflow. Show three expressions that will overflow.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇5.12 Type Conversions 下一篇5.1 Arithmetic Operators (1)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Java后端面试实习自 (2025-12-25 09:24:21)
·Java LTS版本有哪些 (2025-12-25 09:24:18)
·2025年,JAVA还值得 (2025-12-25 09:24:16)
·用 C 语言或者限制使 (2025-12-25 08:50:05)
·C++构造shared_ptr为 (2025-12-25 08:50:01)