![](/img/trans.png)
[英]Why my C program unexpectedly terminates when using floor and ceil and rounding functions?
[英]floor() and ceil() functions vs casting to integer in C
我正在編寫一些C代碼,以反復將浮點數向上和向下舍入為整數值。 標准C數學庫包括函數floor()
和ceil()
。 我注意到函數的更快實現是直接轉換為整數:
int up, down;
float test = 1.3548;
up = (int)(test + 1); //ceil()
down = (int)test; //floor()
我做了一個快速檢查,這似乎工作正常。
函數ceil()
和floor()
將返回與您使用的函數不同的數字
up = (int)(test + 1);
down = (int)test;
當你有一個負數。
如果你有:
float test = -1.3548;
up = (int)test; // ceil()
down = (int)(test-1); // floor()
當test
是一個整數時,即使最后一個語句也不是計算floor()
的好方法。
除非你想以不同的方式處理正數和負數,並且test
時的特殊情況是整數,你最好使用ceil()
和floor()
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.