C#模数方程返回错误值

时间:2018-10-19 04:17:12

标签: c# modulus

var newPosition = (position - key) % alphabet.Length;

当position为66时,键为7964且Alphabet.length = 91,即使应该为19,newPosition仍为-72,为什么?

3 个答案:

答案 0 :(得分:0)

请注意,%实际上不是模数,而是余数

static decimal modulus(decimal a, decimal b)
{
  return a - b * Math.Floor(a / b);
}

...

Console.WriteLine( nfmod(66-7964 , 91));

输出

19

Full Demo Here

答案 1 :(得分:0)

将/用于模块

var newPosition = (position - key) / alphabet.Length;

答案 2 :(得分:0)

((position - key) % alphabet.Length + alphabet.Length) % alphabet.Length

有花招