當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python math.trunc()用法及代碼示例

Python math.trunc() 方法

math.trunc() 方法是 math 模塊的庫方法,用於獲取一個數的截斷整數值,它接受一個數(整數或浮點數)並返回截斷為整數的實數。

注意:如果傳遞除數字以外的任何內容,則該方法返回類型錯誤,如果我們傳遞一個字符串 - 它將返回“TypeError:type str 未定義 __trunc__ 方法”

math.trunc() 方法的語法:

    math.trunc(n)

參數: n– 整數或浮點數。

返回值: int– 它返回一個整數值,它是數字的整數部分n

例:

    Input:
    a = 10.23

    # function call
    print(math.trunc(a))

    Output:
    10

用於演示 math.trunc() 方法示例的 Python 代碼

# Python code demonstrate example of 
# math.trunc() method

# importing math module
import math

# numbers 
a = 10
b = 10.23
c = -10
d = -10.67
e = 10.67

# printing the fractional and integer part 
# of the numbers by using math.trunc()

print("trunc(a):", math.trunc(a))
print("trunc(b):", math.trunc(b))
print("trunc(c):", math.trunc(c))
print("trunc(d):", math.trunc(d))
print("trunc(e):", math.trunc(e))

輸出

trunc(a): 10
trunc(b): 10
trunc(c): -10
trunc(d): -10
trunc(e): 10


相關用法


注:本文由純淨天空篩選整理自 math.trunc() method with example in Python。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。