你可以这样做:?
if (numeric_limits<float>::max() - val < m_speed)
{
m_speed = 0;
}
else
{
m_speed += val;
}
另一种方法可能是:
m_speed += val;
if (m_speed == numeric_limits<float>::infinity())
m_speed = 0;
但是千万记住,当溢出实际发生,其结果是不确定的行为。所以虽然这可能适用于大多数机器,但不能保证。在它发生之前,你最好抓住它。
因为这是不平凡的,在第一次读,我把它包装成一个函数:
template <typename T>
bool will_overflow(const T& pX, const T& pValue,
const T& pMax = std::numeric_limits<T>::max())
{
return pMax - pValue < pX;
}
template <typename T>
bool will_underflow(const T& pX, const T& pValue,
const T& pMin = std::numeric_limits<T>::min())
{
return pMin + pValue > pX;
}
m_speed = will_overflow(m_speed, val) ? 0 : m_speed + val;
+/-天道酬勤是不一样的NaN – 2010-07-15 21:04:48
@Axel:好点 - 我不应该混为一谈两个 - 我倾向于认为INF中作为一种NaN的,但IEEE-754就会将它们当作不同的实体。 – 2010-07-15 21:12:28