c及c++中的取模运算
2015-06-18 22:34
567 查看
首先看C++中两个涉及到模运算的操作:
上述两个操作的结果分别为-1和1。为何会这样呢?
首先引述下2011年的ISO标准:
ISO14882:2011(e) 5.6-4: The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined.
For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.
于是我们可知:
注意标准ISO14882:2003(e)中的如下叙述并没有继续在标准ISO14882:2011(e)中出现,换句话说在新标准中除法运算以及取模运算的结果都是确定的,不再是由某个实现来定义。
If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
std::cout << (-7 % 3) << std::endl; std::cout << (7 % -3) << std::endl;
上述两个操作的结果分别为-1和1。为何会这样呢?
首先引述下2011年的ISO标准:
ISO14882:2011(e) 5.6-4: The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined.
For integral operands the / operator yields the algebraic quotient with any fractional part discarded; if the quotient a/b is representable in the type of the result, (a/b)*b + a%b is equal to a.
于是我们可知:
(-7/3) => -2 -2 * 3 => -6 so a%b => -1 (7/-3) => -2 -2 * -3 => 6 so a%b => 1
注意标准ISO14882:2003(e)中的如下叙述并没有继续在标准ISO14882:2011(e)中出现,换句话说在新标准中除法运算以及取模运算的结果都是确定的,不再是由某个实现来定义。
If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.
相关文章推荐
- 水仙花数
- C++内存分配方式详解——堆、栈、自由存储区、全局/静态存储区和常量存储区
- C语言一些细节
- 冒泡排序与快速排序
- C语言找出字符串中的特定的字符,并输出
- c++ 继承多个类 及虚函数
- 夕甲甲——孔乙己之C++版
- 排序算法——堆排序
- c++字符串的包含问题
- 黑马程序员——C语言关键字、标识符、注释、数据类型、常量
- c++的设计模式之备忘录模式
- C++: std::string 与 Unicode 如何结合?
- LeetCode | Majority Element
- C++ MFC常用函数(转)
- C语言实现for循环输出图案
- C语言指针总结
- C++内存管理
- C/C++ 马踏棋盘实现
- C/C++读取文件名(Windows)
- 进程、线程同步互斥学习 —— 临界区