此代码有一个整洁的错误。
错误指出: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);
答案 0 :(得分:1)
有人可以解释这是为什么以及如何纠正吗?
变窄:浮点数小于double,类似于int8_t小于int16_t。最大浮点比最大浮点小很多。
还请注意:较小的int将自动神奇地提升为较大的int。同样,您的编译器也没有反对“ double x_pos = clownfish-> xPos();”,double总是足够大以包含浮点数。
如何更正:
如果您确信浮动(较小的值)足以满足您的需要,或者您不允许更改小丑鱼代码,那么您可以考虑使用强制转换。
clownfish->xPos(static_cast<float>(x_pos)).
如果您愿意且不受禁止地更改clownfish代码,请确保clownfish x位置(即“ clownfish-> xPos()”返回的值)为双精度,并且确保函数“ clownfish-> xPos()” ”会返回双精度值。
答案 1 :(得分:0)
警告消息指出了问题所在:““将'double'转换为'float'的过程变窄。” cpp core guidelines解释了为什么这可能是一个问题。
假定clownfish->xPos
函数采用float参数。请将函数更改为双精度,以免丢失精度。或对x_pos
使用float,这样就不会失去精度。更普遍的是,不要混合使用float和willy-nilly。