我似乎记得ANSI C没有指定当模运算符的操作数为负时应该返回什么值(只是它应该是一致的).它是否稍后被指定,或者是否总是被指定并且我记得不正确?
可能重复:同时
划分和获取剩余?
是否可以在一个步骤中同时得到整数除法的商和余数,即不进行两次整数除法?
对于由范围R = [ x,y ] 限制的任何整数输入W,由于缺少更好的项,"溢出"是W对R的.如果W超过y,这会导致它回绕.W % (y-x+1) + x
作为这个原则的一个例子,假设我们迭代一个日历的月份:
int this_month = 5;
int next_month = (this_month + 1) % 12;
Run Code Online (Sandbox Code Playgroud)
其中两个整数都在0到11之间(包括0和11).因此,上面的表达式将整数"钳制"到范围R = [0,11].这种使用表达式的方法简单,优雅且有利,因为它省略了分支.
现在,如果我们想要做同样的事情,但倒退呢?以下表达式有效:
int last_month = ((this_month - 1) % 12 + 12) % 12;
Run Code Online (Sandbox Code Playgroud)
但这是深奥的.它怎么能被美化?
tl; dr - 可以((x-1) % k + k) % k进一步简化表达吗?
注意:指定C++标记,因为其他语言以不同方式处理模运算符的负操作数.
编写代码以确定数字是否可被3整除.函数的输入是单个位,0或1,如果到目前为止接收的数字是可被3整除的数字的二进制表示,则输出应为1,否则零.
例子:
input "0": (0) output 1
inputs "1,0,0": (4) output 0
inputs "1,1,0,0": (6) output 1
Run Code Online (Sandbox Code Playgroud)
这是基于面试问题.我要求绘制逻辑门,但由于这是stackoverflow,我会接受任何编码语言.硬件实现的奖励点(verilog等).
部分a(简单):第一个输入是MSB.
b部分(稍微难一点):第一个输入是LSB.
c部分(困难):哪一个更快更小,(a)或(b)?(理论上不是Big-O意义上的,但实际上更快/更小.)现在采用较慢/较大的一个,并使其快/小与更快/更小的一个.
可能重复:
负数的Mod正在融化我的大脑!
我想知道是否有一个更好的算法,我正在尝试做什么:
wrapIndex(-6, 3) = 0 wrapIndex(-5, 3) = 1 wrapIndex(-4, 3) = 2 wrapIndex(-3, 3) = 0 wrapIndex(-2, 3) = 1 wrapIndex(-1, 3) = 2 wrapIndex(0, 3) = 0 wrapIndex(1, 3) = 1 wrapIndex(2, 3) = 2 wrapIndex(3, 3) = 0 wrapIndex(4, 3) = 1 wrapIndex(5, 3) = 2
我想出来了
function wrapIndex(i, i_max) {
if(i > -1)
return i%i_max;
var x = i_max + i%i_max;
if(x == i_max)
return 0;
return x;
}
有没有更好的方法来做到这一点?
一直在搜索ios中的mod运算符,就像%在c中一样,但没有找到它的运气.尝试在此链接中的答案,但它给出了相同的错误.我有一个浮点变量'rotationAngle',其角度根据用户的手指移动保持递增或递减.有点像这样:
if (startPoint.x < pt.x) {
if (pt.y<936/2)
rotationAngle += pt.x - startPoint.x;
else
rotationAngle += startPoint.x - pt.x;
}
rotationAngle = (rotationAngle % 360);
}
Run Code Online (Sandbox Code Playgroud)
我只需要确保rotationAngle不超过+/- 360限制.任何帮助任何身体.谢谢
rem给出了这个:
Prelude> rem 9 8
1
Run Code Online (Sandbox Code Playgroud)
我想要这样的东西:
Prelude> nonIntRem 9.1 8
1.0999999999999996
Run Code Online (Sandbox Code Playgroud)
我这样实现了:
nonIntRem x y = x - (y * (fromIntegral $ truncate (x/y)))
Run Code Online (Sandbox Code Playgroud)
我的问题是:
是否可以使用nth-childwith modulo?我知道你可以指定一个公式,比如
nth-child(4n+2)
Run Code Online (Sandbox Code Playgroud)
但我似乎无法找到是否有模运算符.我在下面尝试了以下示例,但似乎都没有效果:
nth-child(n%7)
nth-child(n % 7)
nth-child(n mod 7)
Run Code Online (Sandbox Code Playgroud) 例如,(-3) % 2将返回-1而不是1.
在Scala中获得正余数的首选方法是什么?如(((-3) % 2) + 2) % 2,或abs(-3 % 2)?