新聞中心
在Python中,round()函數(shù)是一個(gè)內(nèi)置的數(shù)學(xué)函數(shù),用于對(duì)浮點(diǎn)數(shù)進(jìn)行四舍五入,它可以將一個(gè)浮點(diǎn)數(shù)四舍五入到指定的小數(shù)位數(shù),round()函數(shù)的基本語(yǔ)法如下:

round(number, ndigits)
number是要四舍五入的浮點(diǎn)數(shù),ndigits是要保留的小數(shù)位數(shù),如果省略ndigits參數(shù),則默認(rèn)保留整數(shù)部分。
下面是一些使用round()函數(shù)的示例:
1、對(duì)一個(gè)浮點(diǎn)數(shù)進(jìn)行四舍五入:
num = 3.14159 rounded_num = round(num) print(rounded_num) # 輸出:3
2、對(duì)一個(gè)浮點(diǎn)數(shù)進(jìn)行指定位數(shù)的四舍五入:
num = 3.14159 rounded_num = round(num, 2) print(rounded_num) # 輸出:3.14
3、對(duì)一個(gè)列表中的浮點(diǎn)數(shù)進(jìn)行四舍五入:
numbers = [1.23, 2.34, 3.45, 4.56] rounded_numbers = [round(num) for num in numbers] print(rounded_numbers) # 輸出:[1, 2, 3, 4]
4、對(duì)一個(gè)列表中的浮點(diǎn)數(shù)進(jìn)行指定位數(shù)的四舍五入:
numbers = [1.23, 2.34, 3.45, 4.56] rounded_numbers = [round(num, 2) for num in numbers] print(rounded_numbers) # 輸出:[1.23, 2.34, 3.45, 4.56]
5、對(duì)一個(gè)字符串表示的浮點(diǎn)數(shù)進(jìn)行四舍五入:
num_str = "3.14159" num = float(num_str) rounded_num = round(num) print(rounded_num) # 輸出:3
6、對(duì)一個(gè)字符串表示的浮點(diǎn)數(shù)進(jìn)行指定位數(shù)的四舍五入:
num_str = "3.14159" num = float(num_str) rounded_num = round(num, 2) print(rounded_num) # 輸出:3.14
7、對(duì)一個(gè)元組中的浮點(diǎn)數(shù)進(jìn)行四舍五入:
numbers = (1.23, 2.34, 3.45, 4.56) rounded_numbers = tuple(round(num) for num in numbers) print(rounded_numbers) # 輸出:(1, 2, 3, 4)
8、對(duì)一個(gè)元組中的浮點(diǎn)數(shù)進(jìn)行指定位數(shù)的四舍五入:
numbers = (1.23, 2.34, 3.45, 4.56) rounded_numbers = tuple(round(num, 2) for num in numbers) print(rounded_numbers) # 輸出:(1.23, 2.34, 3.45, 4.56)
通過(guò)以上示例,我們可以看到,round()函數(shù)在Python中非常實(shí)用,可以方便地對(duì)浮點(diǎn)數(shù)進(jìn)行四舍五入操作,需要注意的是,對(duì)于非數(shù)字類(lèi)型的數(shù)據(jù),round()函數(shù)會(huì)拋出TypeError異常,在使用round()函數(shù)時(shí),請(qǐng)確保傳入的數(shù)據(jù)是浮點(diǎn)數(shù)類(lèi)型。
本文題目:python中的round函數(shù)
瀏覽路徑:http://m.fisionsoft.com.cn/article/cohsggo.html


咨詢(xún)
建站咨詢(xún)
