2
def hailstone(n):
    print(n,end=' ')
    
    while n!=1:
        if n%2==1:
            n=3*n+1  
            print(n,end=' ')
        else:
            n=n/2
            print(n,end=' ')
            
hailstone(7)

Output: 7 22 11.0 34.0 17.0 52.0 26.0 13.0 40.0 20.0 10.0 5.0 16.0 8.0 4.0 2.0 1.0

Hello, I wonder why python prints these integer numbers as float numbers after 22. Thanks.

Barmar
  • 741,623
  • 53
  • 500
  • 612
blitz1
  • 77
  • 5

1 Answers1

3

In Python 3, a/b is a float division so your 22/2 is 11.0

But a//b is integer division so 22//2 is 11.

But also 23//2 is 11, mind you ... but you are only dividing by 2 in even cases anyway, so you shouldn't be concerned with losing fractional parts.

JimN
  • 340
  • 2
  • 10