您的位置:首页 > 运维架构

The mod(%) operation 负数取模运算详解

2015-08-13 22:07 435 查看
Please indicate the source if you want to reprint: http://blog.csdn.net/gaoxiangnumber1

If a and d are integers, d is not zero, then the remainder r fits the formula:

a = q*d + r

q is an integer, and 0 ≤ |r| < |d|.

For C++/Java, the mod operation satisfy the following rules:

When a and d have the same symbol, the result of a%d is to make q as small as possible.

When a and d don’t have the same symbol, the result of a%d is to make q as big as possible.

Test program:

[code]#include<iostream>
using namespace std;

int main()
{
    cout<<20%3<<endl;
    cout<<(-20)%(-3)<<endl;
    cout<<(-3)%(-20)<<endl;
    cout<<(-20)%(3)<<endl;
    cout<<(20)%(-3)<<endl;
    cout<<(-3)%(20)<<endl;
    cout<<(3)%(-20)<<endl;

    return 0;
}


Result:

2

-2

-3

-2

2

-3

3

Please indicate the source if you want to reprint: http://blog.csdn.net/gaoxiangnumber1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: