2016-01-21 68 views
1

編寫一個程序,要求用戶輸入一個浮點數,然後對其應用sqrt()連續10次。以兩種不同的方式計算結果。 (提示:SQRT()實際上是一個冪。)計算用戶輸入編號的平方根

這是我的了:

from math import * 

def main(): 
    n = eval(input("Please enter a whole number: ")) 
    fact = 1 
    for i in range(10): 
     n = sqrt(n)*fact 
    print("In",i+1 , "The sqrt of :", n , "is", n) 

main() 

我想表明這樣的:例如,輸入一個數字:16

在1 ,16的SQRT是4

2,4的平方根是2

... ...

10,sqrt .. ..是

請幫忙嗎?

+2

重型暗示'的sqrt(x)的== X^0.5' –

+0

使用'int'(或'float',如果你想接受浮點值),而不是'eval'。 – chepner

+0

你有沒有更進一步? – timgeb

回答

0

這是你的更正後的代碼:

from math import * 

def main(): 
    n = float(input("Please enter a whole number: ")) 
    for i in range(10): 
     n = sqrt(n) 
     print("In",i+1 , "The sqrt of :", n , "is", n) 

main() 

您需要用戶輸入轉換爲浮子和fact變量。 eval短語錯誤。

「第二」這樣做的方法是使用** 0.5

def other(): 
    n = float(input("Please enter a whole number: ")) 
    for i in range(10): 
     n = n ** 0.5 
     print("In", i+1 , "The sqrt of :", n , "is", n) 

other() 

雖然我不知道你爲什麼會需要它在兩個方面。

+0

你的意思是'**',而不是'^'。 –

+0

@HughBothwell好點,編輯 –

0

這裏的其他 /優雅申請平方根n次的方法:如果你正在使用Python2

>>> def comp_nth_sqrt(x, n): 
...  return x**(0.5**n) 
... 
>>> comp_nth_sqrt(4, 1) 
2.0 
>>> comp_nth_sqrt(4, 2) 
1.4142135623730951 
>>> comp_nth_sqrt(4, 10) 
1.0013547198921082 

,請使用

x = int(raw_input()) 

,如果你使用的是Python3,請使用

x = int(input()) 

得到您的電話號碼。 eval是不需要的,大部分時間是邪惡的。

0
## Write a program to check if the input is accept square root or not 
## If it accept print the square root if not print sorry..etc 
import math 

num_sqrt = float(input("Enter number to get the Square root : ")) 
num_sqrt = math.sqrt(num_sqrt)  #to find the square root 
num_sqrt = str(num_sqrt)   #float to string 
n = num_sqrt[len(num_sqrt)-2]  #to find "." 
if n == "." :      
    num_sqrt = float(num_sqrt) 
    print(num_sqrt) 
else : 
    print("Sorry this number doesn't have square root")