gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:04:50 25 4
gpt4 key购买 nike

这段代码有一个 clang-tidy 错误。

错误状态:Narrowing conversion from 'double' to '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 小很多。

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


如何改正:

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

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

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com