python 2.6 docs声明x % y
被定义为x/y的剩余部分(http://docs.python.org/library/stdtypes.html#numeric-types-int-float-long-complex).我不知道究竟发生了什么,如:
for i in range(2, 11):
print 1.0 % i
Run Code Online (Sandbox Code Playgroud)
打印"1.0"十次,而不是像我预期的那样"0.5,0.333333,0.25"等(1/2 = 0.5等).
cod*_*gic 10
模数在整数上下文中执行,而不是小数(余数是整数).因此:
1 % 1 = 0 (1 times 1 plus 0)
1 % 2 = 1 (2 times 0 plus 1)
1 % 3 = 1 (3 times 0 plus 1)
6 % 3 = 0 (3 times 2 plus 0)
7 % 3 = 1 (3 times 2 plus 1)
8 % 3 = 2 (3 times 2 plus 2)
etc
Run Code Online (Sandbox Code Playgroud)
如何获得x/y的实际余数?
我认为你的意思是做一个常规的浮点除法?
for i in range(2, 11):
print 1.0 / i
Run Code Online (Sandbox Code Playgroud)
我认为你可以通过做这样的事情得到你想要的结果:
for i in range(2, 11):
print 1.0*(1 % i) / i
Run Code Online (Sandbox Code Playgroud)
这计算其他人解释的(整数)余数.然后再次除以分母,以产生商的小数部分.
注意,我将模运算的结果乘以1.0,以确保完成浮点除法运算(而不是整数除法,这将导致0).
归档时间: |
|
查看次数: |
42586 次 |
最近记录: |