x= float(raw_input("enter a number: ")) ans =0 while ans*ans*ans < abs(x): ans=ans+.01 if ans*ans*ans!= abs(x): print x, ' is not a perfect cube' else: if x<0: ans=-ans print "the cube of "+str(x)+' is '+str(ans) ## can anyone please let me know what have i done wrong and how to fix it. I replaced 1 with .01 for the incremental. now even if i enter a number that has a perfect cube, the program cannot identify it. i still want to use .01 incremental value
There you go! x = float(input("enter a number: ")) ans = 0 while (ans*ans*ans) < abs(x): ans= ans+.01 ans = round(ans, 1) if (ans*ans*ans) == x : print('the cube of ' + str(x) + ' is ' + str(ans)) else: print(str(x)+ ' is not a perfect cube')
val = float(raw_input("Enter a number: ")) ans = 0 while (ans**3) < abs(val): ans = ans + 0.01 print ans, 'is ans' # by adding this print statement you can see the value of ans each time the loop # executes. If you use the the value 9 as an input, you'll see that the last value of ans # is 2.09. But 2.09 * 2.0 9 * 2.09 = 9.129...... Since this value does not == 9. Then, # the program outputs that 9 is not a perfect square. if ans**3 != abs(val): print val, 'is not a perfect cube' else: if val < 0: ans = -ans print 'the cube of', val, 'is', ans # the solution to this problem is addressed by comparing the resulting 9.129... value # with the inputted value of 9 using an epsilon value. The comparison is: if 9.129 is # close enough to 9, then it (9) is a perfect square. This concept is covered in # lecture 3.
Join our real-time social learning platform and learn together with your friends!