user1624992
user1624992

Reputation: 1

Integer Finder Issue

I am trying to make a function that finds the number you want with this code:

def get(x):
    y=1
    while (x/y != 1):
        y= y+1
    return y

But it keeps giving me one half of the answer + 1. Like, if I put in 6 it gives me 4, and if i put in 500 it gives me 251.

Upvotes: 0

Views: 72

Answers (2)

Mutant
Mutant

Reputation: 3821

I think this what you are looking for -

 def get(x):
     y=1.0
     while (x/y != 1):
             print y, x
             y= y+1
     return y

try below function call -

>>> get(5.0)

1 and 1.0 is does the trick. Check out the python documentation for more understanding!

Upvotes: 0

mgilson
mgilson

Reputation: 310089

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.

Upvotes: 1

Related Questions