Click here to Skip to main content
15,919,245 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
My code is as below:
Python
s = 18
x = 0.000
g = 0
a = -1
for n in range(0,3):
    while((x+(a/10**(n)))**2 <= s and x <= s/2 and a <= 9):
        a = a+1
        x = x + a/10**(n)
        g = g+1
        print(x)
        print(g)
        print(n)
        print(a)

y = format(x,'.2f')
y


What I have tried:

I am getting 4.00 as answer. I wanted to know why am I not able to go beyond 4.0 and check for 4.1 and so on.
Posted
Updated 26-Dec-17 9:00am
v2
Comments
Richard MacCutchan 26-Dec-17 14:55pm    
Please format your code properly between <pre> tags, so we can see the indenting.

In Python 3, y is 4.20.

In Python 2, it is 4.00 indeed, so I assume you're using that version. And there is the cause: in Python 2, division between two integers returns an integer as well, whereas you actually want a floating-point number as result. (In Python 3, division is floating-point division by default and // does integer division)

There are two possible solutions to fix this:

One way is to make all your initial variables floats, like this:
Python
s = 18.0
x = 0.000
g = 0.0
a = -1.0
Now all divisions (e.g. a / 10) are float / int divisions, which result in a float.

Another option, which does not require the above, is to tell Python to use floating-point division in all cases, by adding this line to the top of your code file:
Python
from __future__ import division
 
Share this answer
 
I just ran this and got the following output:
x:  0.0
g:  1
n:  0
a:  0
x:  1.0
g:  2
n:  0
a:  1
x:  3.0
g:  3
n:  0
a:  2
x:  3.3
g:  4
n:  1
a:  3
x:  3.6999999999999997
g:  5
n:  1
a:  4
x:  4.199999999999999
g:  6
n:  1
a:  5
y:  4.20
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900