我如何在 C++ 中做模数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2581594/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I do modulus in C++?
提问by user161190
How do I perform a mod operation between two integers in C++?
如何在 C++ 中的两个整数之间执行模运算?
回答by wilhelmtell
C++ has the %
operator, occasionally and misleadingly named "the modulus" operator. In particular the STL has the modulus<>
functor in the <functional>
header. That's not the mathematical modulus operator, mind you, because in modulus arithmetics a mod b
by definition evaluates to a non-negative value for any value of a
and any positive value of b
. In C++ the sign of the result of a % b
is implementation-definedif either of the arguments is negative. So, we would more appropriately name the %
operator the remainderoperator.
C++ 有%
运算符,偶尔会误导性地命名为“模数”运算符。特别是 STLmodulus<>
在<functional>
头文件中有函子。请注意,这不是数学模数运算符,因为a mod b
根据定义,在模数算术中,对于 的任何值a
和任何正值,计算结果为非负值b
。在 C++ 中,如果任一参数为负,则结果的符号a % b
是实现定义的。因此,我们将%
运算符命名为余数运算符更合适。
That said, if you truly want the mathematical modulus operator then you can define a function to do just that:
也就是说,如果你真的想要数学模运算符,那么你可以定义一个函数来做到这一点:
template<typename V>
V mod(const V& a, const V& b)
{
return (a % b + b) % b;
}
So long as b
is a positive value a call to the above function will yield a non-negative result.
只要b
是正值,对上述函数的调用就会产生非负结果。
回答by Jim Lewis
As the other answers have stated, you can use the C++ % operator. But be aware that there's a wrinkle no one has mentioned yet: in the expression a % b
, what if a
is negative?
Should the result of this operation be positive or negative? The C++ standard leaves this up to the
implementation. So if you want to handle negative inputs portably, you should probably
do something like r = abs(a) % b
, then fix up the sign of r
to match your requirements.
正如其他答案所述,您可以使用 C++ % 运算符。但请注意,有一个问题还没有人提到:在表达式中a % b
,如果 a
是负数呢?这个操作的结果应该是正的还是负的?C++ 标准将这留给了实现。因此,如果您想轻松地处理负输入,您可能应该执行类似的操作r = abs(a) % b
,然后修复 的符号r
以符合您的要求。
回答by Giffyguy
Like this: x=y%z
像这样:x=y%z
回答by Klaim
Using the modulus %
operator :
使用模%
运算符:
int modulus_a_b = a % b;
回答by ErdeNese
if you use double variable, you should use;
如果你使用双变量,你应该使用;
double x;
double y;
double result = fmod(x, y);