Perl 中有兩種簡單的方法可以達到:
一種是加上 0.5 後取 int() (positive numbers)
另一種是 sprintf 用 %.0f 控制
不過浮點數本身便有其限制,預設的浮點數在高精度需求的運算是無意義的
底下的範例可以看到,當要求很高的精度時,會有誤差需小心
use 5.016; say int(9.9+0.5); # 10 say int(9.50000000+0.5); # 10 say int(9.49999999+0.5); # 9 say int(9.49999999999999+0.5); # 9 say int(9.49999999999999999999+0.5); # 9? say "-"x20; say sprintf("%0.f", 9.9); # 10 say sprintf("%0.f", 9.50000000); # 10 say sprintf("%0.f", 9.49999999); # 9 say sprintf("%0.f", 9.499999999999999); # 9 say sprintf("%0.f", 9.49999999999999999999); # 9? =output 10 10 9 9 10 -------------------- 10 10 9 9 10 =cut
No comments:
Post a Comment