1. 程式人生 > 程式設計 >python中取絕對值簡單方法總結

python中取絕對值簡單方法總結

python如何使用絕對值?下面給大家介紹三種求絕對值的方法:

importmath

defabs_value1():
a=float(input('1.請輸入一個數字:'))
ifa>=0:
a=a
else:
a=-a
print('絕對值為:%f'%a)

defabs_value2():
a=float(input('2.請輸入一個數字:'))
a=abs(a)
print('絕對值為:%f'%a)

defabs_value3():
a=float(input('3.請輸入一個數字:'))
a=math.fabs(a)
print('絕對值為:%f'%a)

abs_value1()
abs_value2()
abs_value3()

結果如下:

1.請輸入一個數字:-1
絕對值為:1.000000
2.請輸入一個數字:0
絕對值為:0.000000
3.請輸入一個數字:2
絕對值為:2.000000

基礎知識點擴充套件:

Python abs() 函式

abs() 函式返回數字的絕對值。

以下是 abs() 方法的語法:

abs( x )

引數

x -- 數值表示式。

返回值

函式返回x(數字)的絕對值。

例項

以下展示了使用 abs() 方法的例項:

#!/usr/bin/python
 
print "abs(-45) : ",abs(-45)
print "abs(100.12) : ",abs(100.12)
print "abs(119L) : ",abs(119L)

以上例項執行後輸出結果為:

abs(-45) : 45
abs(100.12) : 100.12
abs(119L) : 119

以上就是python中取絕對值簡單方法總結的詳細內容,更多關於如何在python中取絕對值的資料請關注我們其它相關文章!