關於python3四捨五入的問題

2022-08-02 19:36:12 字數 1242 閱讀 1338

最近在做面試題,如下:

依次輸入乙個學生的學號,以及3科(c語言,數學,英語)成績,在螢幕上輸出該學生的學號,3科成績。

學號以及3科成績,學號和成績之間用英文分號隔開,成績之間用英文逗號隔開。
學號,3科成績,輸出格式詳見輸出樣例。
示例1

17140216;80.845,90.55,100.00

the each subject score of  no. 17140216 is 80.85, 90.55, 100.00.

選擇用python做的話:很容易就寫出來如下**:

s_input = input()

a,b = s_input.split(";")

s1,s2,s3 = b.split(",")

print("the each subject score of no. %s is %.2f, %.2f, %.2f."%(a,round(float(s1),2),round(float(s2),2),round(float(s3),2)))

然後發現與題目要求的輸出結果不一致,80.845四捨五入得到的是80.84

那如何能得到正確的四捨五入結果呢?

於是自己寫乙個四捨五入的函式:

from decimal import decimal, round_half_up

def rdec(x):

return decimal(x).quantize(decimal('0.00'), rounding=round_half_up)

這個函式的傳參,建議用字串,如果是浮點數的話,浮點值在計算機裡面不能被精確儲存,那麼它會先被轉換為乙個不精確的二進位制值,然後再把這個不精確的二進位制值轉換為等效的十進位制值,這樣得到的四捨五入的值肯定是有偏差的

然後這個面試題的答案如下:

from decimal import decimal, round_half_up

def rd(x):

return decimal(x).quantize(decimal('0.00'), rounding=round_half_up)

s_input = input()

a,b = s_input.split(";")

s1,s2,s3 = b.split(",")

print("the each subject score of no. %s is %s, %s, %s."%(a,rd(s1),rd(s2),rd(s3)))

關於四捨五入

四捨五入 轉http nssoft.showdoc.asp?did 267 delphi的四捨五入函式round,對於 5的情況,整數部分是奇數,那麼會round up,偶數會round down,例如 x round 17.5 x 18 x round 12.5 x 12 請使用下面的函式代替ro...

qt的四捨五入 Qt(C )四捨五入

qt現在是四捨六入五成雙,要想四捨五入得自己想辦法,實現如下 include include double c1 3.435 double c2 3.445 double c3 3.4351 double c4 3.4451 double c5 3.445 qdebug qdebug qdebug ...

mysql 金額 四捨五入 mysql四捨五入

雲資料庫 mysql 雲資料庫 rds for mysql 是穩定可靠 可彈性伸縮的雲資料庫服務。通過雲資料庫能夠讓您幾分鐘內完成資料庫部署。雲端完全託管,讓您專注於應用程式開發,無需為資料庫運維煩惱 低至 0.24 小時起,買1年83折 雲資料庫mysql 雲資料庫 rds for mysql 是...