是的,你保證到達那裏。對有關數字進行處理操作後發生浮點不精確。常量在你的情況下是安全的。
但是,如果通過提供過多的小數來超出浮點數精度,或者您使用另一種數據類型初始化浮點數,它可能會得到不同的解釋。
舉例來說,這可能不是讓它:
float foo{2.1234321f};
if (foo * 6.1234321f/0.1234321f == 105.3428750f)
{
// Am I always guaranteed to get here? Not at all.
}
如果你想比較浮點數時,爲了安全起見,你應該「近似」的結果。請參閱下面的代碼。
#include <limits>
#include <type_traits>
using namespace std;
class exact{};
class approx{};
template<class> struct tolerance;
template<>
struct tolerance<float>
{
static constexpr float value() { return 0.00001; }
}
template<class T>
bool close_enough(T a, T b, exact)
{
return a == b;
}
template<class T>
bool close_enough(T a, T b, approx)
{
return abs(a - b) <= tolerance<T>::value();
}
template<class T>
bool close_enough(T a, T b)
{
return close_enough(a, b,
conditional<numeric_limits<T>::is_exact, exact, approx>::type{});
}
int main()
{
float a = 2.1234321f, b = 105.3428750f;
if (close_enough(a * 6.1234321f/0.1234321f, b))
{
// Am I always guaranteed to get here? Yes!
}
else
{
// ...
}
}
注意_integer_類型和_pointers_的值表示也是實現定義的。而且我們肯定會期望這對整數有效,指針不是嗎? –
是的。但是,浮點運算會因舍入錯誤而受到影響,因此在浮點運算完成後您將無法得到保證。 – phantom
個名堂浮動(0)等於任何浮點/整數0無論implementaion –