我正在尝试使用此代码创建一个函数来查找您想要的数字:
def get(x):
y=1
while (x/y != 1):
y= y+1
return y
但它一直给我答案的一半 + 1。就像,如果我输入 6,它给我 4,如果我输入 500,它给我 251。
Your problem is that it is doing integer division. So, 6/4
evaluates to 1. (In python3, true division would kick in and I think your test would work)
The best way to fix this would be to do something like:
while x != y:
...
And of course, these tests should really only be done using integers...once you pass a floating point number in, it's hard to say what will happen.
我认为这就是您要寻找的-
def get(x):
y=1.0
while (x/y != 1):
print y, x
y= y+1
return y
试试下面的函数调用 -
>>> get(5.0)
1 和 1.0 可以解决问题。查看 python 文档以获得更多理解!