正常值为浮点数

来源:互联网 发布:上海网络通讯设备回收 编辑:程序博客网 时间:2024/04/27 14:51
你已经看到了所有这些工作的方式,而且它们非常直观。每个操作符求值为布尔值true(1)或false(0)。


下面是一些使用整数运算符的示例代码:

#include <iostream> int main(){    std::cout << "Enter an integer: ";    int x;    std::cin >> x;     std::cout << "Enter another integer: ";    int y;    std::cin >> y;     if (x == y)        std::cout << x << " equals " << y << "\n";    if (x != y)        std::cout << x << " does not equal " << y << "\n";    if (x > y)        std::cout << x << " is greater than " << y << "\n";    if (x < y)        std::cout << x << " is less than " << y << "\n";    if (x >= y)        std::cout << x << " is greater than or equal to " << y << "\n";    if (x <= y)        std::cout << x << " is less than or equal to " << y << "\n";     return 0;}

这些运算符在比较整数时使用非常简单。


浮点数比较


使用这些操作符直接比较浮点值是危险的。这是因为浮点操作数中的小舍入错误可能会导致意外结果。我们在第2.5节详细讨论舍入误差——浮点数。


下面是舍入错误导致意外结果的示例:

#include <iostream> int main(){    double d1(100 - 99.99); // should equal 0.01    double d2(10 - 9.99); // should equal 0.01     if (d1 == d2)        std::cout << "d1 == d2" << "\n";    else if (d1 > d2)        std::cout << "d1 > d2" << "\n";    else if (d1 < d2)        std::cout << "d1 < d2" << "\n";        return 0;}


有时需要做的比较unavoidable浮点冰。在这情况下,小于和经营者为大于(>,<,>,=,=,<鸭子)或是使用与正常值为浮点数。所谓的运营商将产生正确的结果,大部分时间没有潜在的,只有当两operands是关闭的。鸽子的方式运营的两个男人是用来一个错误的结果,往往只是有轻微影响。《冰多享受平等的troublesome自平衡的smallest大学rounding inaccurate使得它完全错误。因此,利用运营商或运营商= =!对浮点数= advised冰槽。最常见的方法是平等的involves浮点功能,采用calculates如何关闭的两个值是每个其他。如果两个数是“近了”,那么,我们叫他们的平等。“价值”关闭用来代表了传统所谓的“冰星。

原创粉丝点击