简体   繁体   中英

C# modulus equation return wrong value

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

当position为66时,键为7964,并且Alphabet.length = 91时,newPosition以某种方式为-72,即使应该为19。为什么?

Be aware % is actually not a modulus its a remainder

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

...

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

Ouput

19

Full Demo Here

使用/用于模块

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

绝招

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM