你可以這樣做:?
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