C++ int 型负数除法与求模运算

来源:互联网 发布:淘宝怎么做免费推广 编辑:程序博客网 时间:2024/05/17 08:41

C++ int 型负数除法与求模运算


       一、结论:

       1、除法运算:向零取整(向0方向取最接近精确值的整数,类比向上取整和向下取整)

       比如:10/(-4) = -2;10/4 = 2;

       2、求模运算: (1) |小| % |大| = |小| ,符号同前; (2)|大 | % |小| = |余| ,符号同前; (|n|指n的绝对值,求模时参照该公式:“余数=被除数-商*除数

       比如:        3%4 = 3, (-3)%(-4) = -3,(-3)%4 = -3,3%(-4) = 3;   5%3 = 2, (-5)%(-3) = -2,(-5)%3 = -2,5%(-3) = 2;


       二、实验:

#include <iostream>#include <vector>using namespace std;int main(){int unbig = 10, big = -10, unsmall = 4, small = -4; // 大小两个数,一个有符号一个无符号cout << "10/4 = " << unbig / unsmall << endl; // 2cout << "10/(-4) = " << unbig / small << endl; // -2cout << "(-10)/4 = " << big / unsmall << endl; // -2cout << "(-10)/(-4) = " << big / small << endl; // 2cout << endl;cout << "10%4 = " << unbig % unsmall << endl; // 2cout << "10%(-4) = " << unbig % small << endl; // 2cout << "(-10)%4 = " << big % unsmall << endl; // -2cout << "(-10)%(-4) = " << big % small << endl; // -2cout << endl;cout << "4%10 = " << unsmall % unbig << endl; // 4cout << "(-4)%10 = " << small % unbig << endl; // -4cout << "4%(-10) = " << unsmall % big << endl; // 4cout << "(-4)%(-10) = " << small % big << endl; // -4system("pause");return 0;}

        三、实验结果:



       四、参考资料:C/C++除法实现方式及负数取模详解







       
0 0
原创粉丝点击