c++ - Why in C++ do static_cast of negative numbers differ if the number is constant or not
问题描述
What's the C++ rules that means equal is false?. Given:
float f {-1.0};
bool equal = (static_cast<unsigned>(f) == static_cast<unsigned>(-1.0));
E.g. https://godbolt.org/z/fcmx2P
#include <iostream>
int main()
{
float f {-1.0};
const float cf {-1.0};
std::cout << std::hex;
std::cout << " f" << "=" << static_cast<unsigned>(f) << '\n';
std::cout << "cf" << "=" << static_cast<unsigned>(cf) << '\n';
return 0;
}
Produces the following output:
f=ffffffff
cf=0
解决方案
您的程序的行为是未定义的:C++ 标准没有定义负浮点类型到unsigned
类型的转换。
(请注意,熟悉的环绕行为仅适用于负整数类型。)
因此,尝试解释您的程序输出没有什么意义。
推荐阅读
- javascript - 如何获取ajax结果并将其显示在另一个页面上?
- reactjs - 无法从 MediaRecorder.onstop() 中提取 videoURL
- python - 循环坐标搜索优化,使用for循环更新新的优化
- amazon-web-services - Windows 中的 AWS CLI 提供空白输出
- python - 在本地启动 Rasa X 后。我在 Rasa 浏览器中收到错误“请求失败,状态码为 500”
- javascript - Javascript For Each Object in Array contains a property that is Array 检查 If Value Matches
- mongodb - Mongodb删除特定字符串
- javascript - $_SESSION 未使用 Ajax 更新
- r - 长格式到列表中,listFromLong 导致:参数 1 不是向量
- nginx - "strict-origin-when-cross-origin" - 使用 vscode 调试 tornado nginx