c++ - 缩小从 double 到 float 的转换范围

标签 c++ clang tidy

此代码有一个 clang-tidy 错误。

错误指出:缩小从“double”到“float”的转换,其中 xPos() 内显示 x_pos;功能在底部。

有人可以解释一下这是为什么以及如何纠正吗?

    //grab the current position
    double x_pos = clownfish->xPos();

    // move the fish 500pixels/sec in the right direction
    // delta time is measured in milliseconds, so divide by 1000 and multiply
    x_pos += 500 * (game_time.delta.count() / 1000.f);

    // update the position of the clown fish
    clownfish->xPos(x_pos);

最佳答案

Can someone explain why that is and how to correct it?

缩小:Float 小于 double,类似于 int8_t 小于 int16_t。最大的 float 比最大的 double 小很多。

另请注意:较小的 int 会自动神奇地提升为较大的 int。同样,您的编译器不会抗议“double x_pos = clownfish->xPos();”,double 总是足够大以包含 float 。


如何更正:

如果您确信 float(较小的)足以满足您的需求,或者不允许您更改 clown 鱼代码,那么您可以考虑使用强制转换。

clownfish->xPos(static_cast<float>(x_pos)).

如果您愿意且不被禁止更改 clownfish 代码,请确保 clownfish x 位置(即“clownfish->xPos()”返回的内容)是 double 值,并且函数“clownfish->xPos()” "返回一个 double 值。

关于c++ - 缩小从 double 到 float 的转换范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58920892/

相关文章:

c++ - 线程池(大概)锁定条件变量和互斥量的问题

c++ - 具有相对间隙的 CPLEX MIP 提前终止,getBestObjValue 与 getObjValue

c++ - 为什么 libclang 会错误解析带有 .h 前缀的 C++ header ?

c++ - 全特化模板类没有外线虚方法定义

python - 在 Python 中修复损坏的 HTML - Beautifulsoup 不工作

c++ - 如何查看 boost set<cpp_int> 中的下一个和上一个元素

c++ - 未找到 libpng "png_set_longjmp_fn"

xslt - 使用 h2d.xsl 将 HTML 转换为 DITA

c++ - OSX 上 boost::program_options 和 C++11 的链接器错误

xslt - 强制 HTML Tidy 输出 XML(而不是 XHTML),或者强制 XSLTproc 解析 XHTML 文件