本文介绍了是否有模数(不是余数)函数/运算?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rust(像大多数编程语言一样)中,%运算符执行 remainder 操作,而不执行 modulus 操作.这些对于负数的运算具有不同的结果:

In Rust (like most programming languages), the % operator performs the remainder operation, not the modulus operation. These operations have different results for negative numbers:

-21 modulus 4 => 3
-21 remainder 4 => -1
println!("{}", -21 % 4); // -1

但是,我想要模数.

我找到了解决方法((a % b) + b) % b,但是如果已有功能,我不想重新发明轮子!

I found a workaround ((a % b) + b) % b, but I don't want to reinvent the wheel if there's already a function for that!

推荐答案

据我所知,没有模块化算术函数.

在C语言中也会发生这种情况,在C语言中通常会使用您提到的解决方法:(a % b) + b.

This also happens in C, where it is common to use the workaround you mentioned: (a % b) + b.

在C,C ++,D,C#,F#和Java中,%实际上是其余部分.在Perl,Python或Ruby中,%是模数.

In C, C++, D, C#, F# and Java, % is in fact the remainder. In Perl, Python or Ruby, % is the modulus.

语言开发人员并不总是采用正确的数学方法",因此从严格的数学家的角度来看,计算机语言可能看起来很奇怪.关键是模数和余数对于不同的用途都是正确的.

Language developers don't always go the "correct mathematical way", so computer languages might seem weird from the strict mathematician view. The thing is that both modulus and remainder, are correct for different uses.

如果愿意,模量会更数学化,而其余部分(在C系列中)与满足以下条件的普通整数除法一致:(a / b) * b + a % b = a;这是从旧的Fortran中采用的.因此,%最好称为余数,我认为Rust与C是一致的.

Modulus is more mathematical if you like, while the remainder (in the C-family) is consistent with common integer division satisfying: (a / b) * b + a % b = a; this is adopted from old Fortran. So % is better called the remainder, and I suppose Rust is being consistent with C.

您不是第一个注意到这一点的人:

You are not the first to note this:

这篇关于是否有模数(不是余数)函数/运算?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!