在Windows中C99打印功能的正確選擇是什麼?C++ Windows替代版本?
#define lrint(x) (floor(x+(x>0) ? 0.5 : -0.5))
/* and if fesetround(0) behavior is required*/
#define lrint(x) ((int)(x))
是正確的嗎?
在Windows中C99打印功能的正確選擇是什麼?C++ Windows替代版本?
#define lrint(x) (floor(x+(x>0) ? 0.5 : -0.5))
/* and if fesetround(0) behavior is required*/
#define lrint(x) ((int)(x))
是正確的嗎?
lrint
沒有[簡單]單一定義,它執行由C99標準定義的行爲。這是由於lrint
的行爲受到對fesetround
的單獨調用的控制。相反,你應該使用單獨的舍入函數和保證語義來滿足應用程序的期望行爲。
floor(x+(x>0) ? 0.5 : -0.5)
將正確一輪只有正數,而不是負的,因爲地板()舍入到負無窮大,這意味着地板(-7.1)= - 8,和代碼的報價件不能修復:地板(-7.1-0.5)= - 8仍然正確,四捨五入到最接近的整數必須導致-7。 下面的代碼塊不正確的舍入:
return int(x + ((x >= 0.0) ? 0.5 : -0.5));
或者,
return ((x >= 0.0) ? floor(x+0.5) : ceil(x-0.5));
感謝在計算機芯片,修正了.. – 2013-03-10 06:22:16
@Insilico他提供原本如果'fesetround確實工作的代碼(0)'在'lrint'之前被調用。現在,如果'x> = 0'則簡單地產生0,否則爲-1。 – 2013-03-10 06:23:17
我誤讀了文檔 - 我應該寫下'fesetround(FE_TOWARDZERO)',而不是'fesetround(0)'。 – 2013-03-10 06:32:34