C/C++ 中的 nextafter() 和 nexttoward()
本篇我们来看看 C 或 C++ 中 nextafter() 和 nextforward() 函数的作用。这些函数存在于 math.h 或 cmath 库中。
如果这些函数类似于 nextafter(a, b) 和 nextforward(a, b)。这些函数用于查找按 b 方向 a 之后下一个可表示的值。nextforward() 具有更精确的第二个参数 b。
示例
#include <stdio.h> #include <math.h> main () { //The nextafter function() printf ("Smallest representable number after 0 towards 1 : %e\n", nextafter(0.0, 1.0)); printf ("Largest representable number before -1 towards 0 :%e\n", nextafter(0.0, -1.0)); printf ("Largest +ve representable number after 0.8 : %e\n", nextafter(0.8, 0.0)); // using nexttoward printf("\n"); printf ("Smallest representable number after 0 towards 1 : %e\n", nexttoward(0.0, 1.0)); printf ("Largest representable number before -1 towards 0 : %e\n", nexttoward(0.0, -1.0)); printf ("Largest +ve representable number after 0.8 : %e\n", nexttoward(0.8, 0.0)); }
输出
Smallest representable number after 0 towards 1 : 4.940656e-324 Largest representable number before -1 towards 0 :-4.940656e-324 Largest +ve representable number after 0.8 : 8.000000e-001 Smallest representable number after 0 towards 1 : 4.940656e-324 Largest representable number before -1 towards 0 : -4.940656e-324 Largest +ve representable number after 0.8 : 8.000000e-001
广告