📜  C / C++中的nextafter()和nexttoward()

📅  最后修改于: 2021-05-30 12:33:48             🧑  作者: Mango

您将如何解决C / C++中的以下问题?

  • C / C++中最小的可表示正浮点数是多少?
  • C / C++中最大的可表示负浮点数是多少?
  • 给定正浮点数x,找到小于x的最大可表示浮点值?

nextafter(x,y)和nexttoward(xy)
在C和C++中,nextafter(x,y)和nexttoward(xy)都是在math.h或cmath头文件中定义的相似函数。它们都在y方向上返回x之后的下一个可表示值。 nexttoward()具有更精确的第二个参数y。

以下程序演示了该概念:

// C program to demonstrate use of nextafter() and nexttoward()
#include 
#include 
int main ()
{
    // using nextafter
    printf ("Smallest positive floating point number : %e\n",
            nextafter(0.0, 1.0));
    printf ("Largest negative floating point number :%e\n",
            nextafter(0.0, -1.0));
    printf ("Largest positive floating point number smaller than 0.5 : %e\n",
            nextafter(0.5, 0.0));
  
    // using nexttoward
    printf ("Smallest positive floating point number : %e\n",
            nexttoward(0.0, 1.0));
    printf ("Largest negative floating point number : %e\n",
            nexttoward(0.0, -1.0));
    printf ("Largest positive floating point number smaller than 0.5 : %e\n",
            nexttoward(0.5, 0.0));
    return (0);
}

输出:

nextafter first value greater than zero: 4.940656e-324
nextafter first value less than zero: -4.940656e-324
nexttoward first value greater than zero: 4.940656e-324
nexttoward first valnextafter first value greater than zero: 4.940656e-324
nextafter first value less than zero: -4.940656e-324
nexttoward first value greater than zero: 4.940656e-324
nexttoward first value less than zero: -4.940656e-324 ue less than zero: -4.940656e-324 
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”