我认为下面的作品,但我会先说明我的假设:
- 浮点数以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