程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[computer test questions (implementation language: python3)] solve cube root

編輯:Python

Title Description
Calculate the cube root of a number , Don't use library functions .
Keep one decimal place .

Input description :

 Parameters to be solved , by double type ( A real number )

Output description :

 Cube root of input parameter . Keep one decimal place .

Example 1
Input

216

Output

6.0

1、 utilize Scanner Receive typed values .
2、 Newton iterative method is used to solve the cube root , Newton's iterative solution formula (1) Shown , Make the entered value y, Defined function , Then the iterative formula of this problem is as follows (2), Until equation (3) Set up stop iteration .
tips: Rounding reservation 1 Decimal places can be used String Static method of format(“%.1f”, x), among % Represents the number of digits before the decimal point ,1 Means to keep the decimal point 1 position ,f Represents the conversion bit float type ( I looked for it. It seems that there is no one who can convert it to double Of )

The code implementation is as follows :

def func():
while True:
try:
a = float(input())
n = 1
while abs(n**3-a) >1e-7:
n = n - (n**3-a)/(3*n**2)
print(round(n,1))
except Exception as e:
#print(e)
break
if __name__ == '__main__':
func()

If using function solutions :

pow(a,1/3)

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved