gpt4 book ai didi

c++ - C++ 中的某个地方是否有 `int` 的正常数学商数和余数?

转载 作者:行者123 更新时间:2023-12-03 22:59:43 25 4
gpt4 key购买 nike

余数总是正的,例如,

remainder(-1, 7) == 6
不是 -1并且商应该向负无穷大舍入,而不是向零舍入,例如,
quotient(-1, 7) == -1
不是 0 .
stdlib 中有这样的函数吗?

最佳答案

Are there any normal mathematical quotient and remainder for int somewhere in C++?

%是余数运算符,但我们可以使用它来几乎让我们到达那里。
实现 Euclidean modulo
 7 modulo  3 -->  1  
7 modulo -3 --> 1
-7 modulo 3 --> 2
-7 modulo -3 --> 2
int modulo_Euclidean(int a, int b) {
int m = a % b;
if (m < 0) {
// m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
m = (b < 0) ? m - b : m + b;
}
return m;
}
另见 Fastest way to get a positive modulo in C/C++其中涵盖了各种陷阱。

关于c++ - C++ 中的某个地方是否有 `int` 的正常数学商数和余数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66878458/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com