简体   繁体   中英

Cube root of a negative number in Python

x = int(raw_input("enter number:"))
ans = 0
while ans**3 < abs(x):
    ans = ans+1
if ans**3 != abs(x):
    print("Not a perfect cube")
else:
    if x < 0:
        ans = -ans
    print(str(ans)+'  '+'is cube root of'+str(x))

This is the correct code..

But when i first tried i left out if x<0: ans=-ans

And got -27 as output

Why am i getting -27, if i don't put ans=-ans, shouldn't i get ans itself as answer..

I'm starting fresh in programming through an online course, sorry for being an ultra n00b..

Thanks

This code works:

x = int(raw_input("Enter an integer: "))

for ans in range(0, abs(x) + 1):
    if ans ** 3 == abs(x):
        break
if ans ** 3 != abs(x):
    print x, 'is not a perfect cube!'
else:
    if x < 0:
        ans = -ans
    print 'Cube root of ' + str(x) + ' is ' + str(ans)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM