%(MOD)的说明 [英] % (mod) explanation

查看:157
本文介绍了%(MOD)的说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天,我写在C#中的程序,我用的以计算某些指标......我的计划我以前不工作,所以我debuged它,我意识到,工作不象其他程序语言,我知道

Today I was writing an program in C# and I used % to calculate some index... my program did't work so I debuged it and I realized that "%" is not working like in other program languages that I know.

例如:

在蟒蛇%的回报值是这样的:

in python % returns values like this:

for x in xrange (-5, 6):
     print x, "% 5 =", x % 5

-5 % 5 = 0
-4 % 5 = 1
-3 % 5 = 2
-2 % 5 = 3
-1 % 5 = 4
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0

在C#中:

for (int i = -5; i < 6; i++)
{
    Console.WriteLine(i + " % 5 = " + i % 5);
}

-5 % 5 = 0
-4 % 5 = -4
-3 % 5 = -3
-2 % 5 = -2
-1 % 5 = -1
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0

我的问题是:

难道我做错了什么或%不能正常工作像它应注意什么?

Did I done something wrong or % is not working like it should?

推荐答案

由于在评论中解释的那样,不同的行为是由设计。不同的语言只是归于不同的含义在运营商

As explained in the comments, the different behaviour is by design. The different languages just ascribe different meanings to the % operator.

您问:

我如何使用模运算在C#?

How can I use modulus operator in C#?

您可以定义一个模运算符自己的行为同样是为Python的运营商:

You can define a modulus operator yourself that behaves the same was as the Python % operator:

int mod(int a, int n)
{
    int result = a % n;
    if ((a<0 && n>0) || (a>0 && n<0))
        result += n;
    return result;
}

这篇关于%(MOD)的说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆