c++ - C++ 中的双变量显示相等,即使它们不相等

标签 c++ c

我刚刚用 C++ 编写了以下代码:

double variable1;
double variable2;
variable1=numeric_limits<double>::max()-50;
variable2=variable1;
variable1=variable1+5;
cout<<"\nVariable1==Variable2 ? "<<(variable1==variable2);

cout 语句的答案是 1,即使 variable2 和 variable1 不相等。有人可以帮我解决这个问题吗?为什么会这样?

我知道不精确 float 学的概念,但不认为直接比较两个 double 会发生这种情况。当我将 variable1 替换为:

double variable1=(numeric_limits<double>::max()-10000000000000);

比较仍然显示它们是相等的。我需要减去多少才能看到它们开始不同?

最佳答案

The maximum value for a double is 1.7976931348623157E+308 .由于缺乏精度,添加和删除小值(例如 50 和 5)实际上不会更改变量的值。因此它们保持不变。

关于c++ - C++ 中的双变量显示相等,即使它们不相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6941733/

相关文章:

c - 如何在C 中存储所有ascii 字符?

c++ - 当我减去内存地址时,为什么结果比我预期的要小?

c - 如何纠正错误 1d 返回 1 退出状态,c

c++ - 相同生成器值的 std::normal_distribution 结果?

c++ - 在渲染 C++ 之前从视频源编辑帧

c++ - Libevent aerospike 客户端::是否可以在我的事件处理机制中注册 Aerospike FD

c - 使用 fscanf 从文件中读取字符串、整数等

c - opengl UI 安全问题

c++ - 如何在不同线程中同时运行多个 QDialogs?

c++ - 为什么发出空的 asm 命令会交换变量?