double类型无误差判断是否相等
作者:
RwChen
,
2023-07-29 21:42:35
,
所有人可见
,
阅读 109
#include <bits/stdc++.h>
using namespace std;
union T {
long long i;
double d;
};
template<typename T>
void print(void *ptr) {
T x = *(T*)ptr;
for (int i = 0; i < 8 * sizeof(T); ++i) {
cout << (x >> i & 1);
}
cout << '\n';
}
template<typename T>
void type(T x) {
cout << "value: " << x << ", size: " << sizeof(T) << ' ' << "bytes\n";
}
int main() {
cin.tie(0)->sync_with_stdio(0);
int n, m;
cin >> n >> m;
double x;
memset(&x, 0x00, sizeof x);
cout << x << '\n';
double y = 0.000000001;
cout << y << '\n';
T test;
test.d = x;
print<long long>(&test.d);
cout << '\n';
test.d = y;
print<long long>(&test.d);
cout << '\n';
void *ptr = &y;
print<long long>(ptr);
type(1.1);
type<int>(1.1);
type(2LL);
return 0;
}
将double转成long long,然后还原成long long,看他们的二进制位是否相等