我認爲下面的作品,但我會先說明我的假設:
- 浮點數以IEEE-754格式存儲在您的實施中,
- 沒有溢出,
- 您有
nextafterf()
可用(它在C99中指定)。
此外,最有可能的是,這種方法效率不高。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char *argv[])
{
/* Change to non-zero for superior, otherwise inferior */
int superior = 0;
/* double value to convert */
double d = 0.1;
float f;
double tmp = d;
if (argc > 1)
d = strtod(argv[1], NULL);
/* First, get an approximation of the double value */
f = d;
/* Now, convert that back to double */
tmp = f;
/* Print the numbers. %a is C99 */
printf("Double: %.20f (%a)\n", d, d);
printf("Float: %.20f (%a)\n", f, f);
printf("tmp: %.20f (%a)\n", tmp, tmp);
if (superior) {
/* If we wanted superior, and got a smaller value,
get the next value */
if (tmp < d)
f = nextafterf(f, INFINITY);
} else {
if (tmp > d)
f = nextafterf(f, -INFINITY);
}
printf("converted: %.20f (%a)\n", f, f);
return 0;
}
在我的機器,它打印:
Double: 0.10000000000000000555 (0x1.999999999999ap-4)
Float: 0.10000000149011611938 (0x1.99999ap-4)
tmp: 0.10000000149011611938 (0x1.99999ap-4)
converted: 0.09999999403953552246 (0x1.999998p-4)
的想法是,我的double
值轉換爲float
值—這可能比這取決於雙值小於或大於舍入模式。當轉換回double
時,我們可以檢查它是小於還是大於原始值。然後,如果float
的值不是正確的方向,我們查看下一個float
號碼的轉換號碼在原始號碼的方向。
上glibc的系統,你會發現一個頭文件ieee754.h,它定義了浮點類型和位域結構,工會,這樣你就可以用尾數和指數更容易,不好意思工作,但我不能給你真正的碼。 – quinmars 2010-01-06 11:23:45