📜  C / C++中的islessequal()

📅  最后修改于: 2021-05-30 18:04:37             🧑  作者: Mango

在C++中,islessequal()是math.h中的预定义函数。用于检查第一个浮点数是否小于或等于第二个浮点。与简单比较相比,它提供的优势是,它在进行比较时不会引发浮点异常。例如,如果两个参数之一是NaN,则它返回false而不引发异常。

句法:

bool isgreaterequal(a, b)

对此的说明如下

// CPP code to illustrate
// the exception of function
#include 
using namespace std;
  
int main()
{
    // Take any values
    float a = 5.5;
    double f1 = nan("1");
    bool result;
  
    // Since f1 value is NaN so
    // with any value of a, the function
    // always return false(0)
    result = islessequal(a, f1);
    cout << a << " islessequal " << f1
         << ": " << result;
  
    return 0;
}

输出:

5.5 islessequal nan: 0

例子:

  • 程序1:
    // CPP code to illustrate
    // the use of islessequal function
    #include 
    using namespace std;
      
    int main()
    {
        // Take two any values
        float a, b;
        bool result;
        a = 5.2;
        b = 8.5;
      
        // Since 'a' is less than
        // equal to 'b' so answer
        // is true(1)
        result = islessequal(a, b);
        cout << a << " islessequal to " << b
             << ": " << result << endl;
      
        int x = 8;
        int y = 5;
      
        // Since 'x' is not less
        // than equal to 'y' so answer
        // is false(0)
        result = islessequal(x, y);
        cout << x << " islessequal to " << y
             << ": " << result;
      
        return 0;
    }
    

    注意:使用此函数,您还可以将任何数据类型与任何其他数据类型进行比较。

  • 程式2:
    // CPP code to illustrate
    // the use of islessequal function
    #include 
    using namespace std;
      
    int main()
    {
        // Take any two values
        bool result;
        float a = 80.23;
        int b = 82;
      
        // Since 'a' is less
        // than equal to 'b' so answer
        // is true(1)
        result = islessequal(a, b);
        cout << a << " islessequal to " << b
             << ": " << result << endl;
      
        char x = 'c';
      
        // Since 'c' ascii value(99) is not
        // less than variable a so answer
        // is false(0)
        result = islessequal(x, a);
        cout << x << " islessequal to " << a
             << ": " << result;
      
        return 0;
    }
    

    输出:

    80.23 islessequal to 82: 1
    c islessequal to 80.23: 0
    

应用范围:
在许多应用程序中,我们可以使用islessequal()函数比较两个值,例如在while循环中使用它来打印前10个自然数。

// CPP code to illustrate
// the use of islessequal function
#include 
using namespace std;
  
int main()
{
    int i = 1;
    while (islessequal(i, 10)) {
        cout << i << " ";
        i++;
    }
    return 0;
}

输出:

1 2 3 4 5 6 7 8 9 10 
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。