假设以下内容:
#include <iostream>
int main()
{
double a = 5.6;
intptr_t b = (intptr_t) a;
double c = (double) b;
return 0;
}
c
将是5
。我的问题是,由于intptr_t
在64位计算机上也为64位(与double相同),为什么在转换过程中不保存精度位?
尽管intptr_t
表示一个指向int的指针,但其下标类型仍然是整数。因此
intptr_t b = (intptr_t)a
仍在截断double
,类似于您刚刚写的内容:
int b = (int)a;
您想做的是获取a
的地址:
intptr_t b = (intptr_t)&a
然后将其转换回
double c = *(double*)b;