use*_*069 7 c double function long-integer
也许它似乎有点罕见的问题,但我想找到一个能够将double(c号)转换为long(c号)的函数.没有必要保留双重信息.最重要的是:
double a,b;
long c,d;
c = f(a);
d = f(b);
Run Code Online (Sandbox Code Playgroud)
这必须是真理:
如果
(a < b)那时c < d为所有人a,b double而且 为所有人c,d long
谢谢你们所有人.
如果满足以下两个条件,则您的要求是可行的:
sizeof(double)相同sizeof(long)虽然第二个条件适用于每个广泛使用的平台,但第一个条件却没有.
如果两个条件都牵着你的平台上,那么你就可以实现如下功能:
long f(double x)
{
if (x > 0)
return double_to_long(x);
if (x < 0)
return -double_to_long(-x);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您有几种不同的方法来实现转换功能:
long double_to_long(double x)
{
long y;
memcpy(&y,&x,sizeof(x));
return y;
}
long double_to_long(double x)
{
long y;
y = *(long*)&x;
return y;
}
long double_to_long(double x)
{
union
{
double x;
long y;
}
u;
u.x = x;
return u.y;
}
Run Code Online (Sandbox Code Playgroud)
请注意,不推荐使用第二个选项,因为它违反了严格别名规则.
从浮点类型到整数类型有四种基本转换:
floor - Rounds towards negative infinity, i.e. next lowest integer.
ceil[ing] - Rounds towards positive infinity, i.e. next highest integer.
trunc[ate] - Rounds towards zero, i.e. strips the floating-point portion and leaves the integer.
round - Rounds towards the nearest integer.
Run Code Online (Sandbox Code Playgroud)
这些转换都不会给出您指定的行为,但floor会允许稍弱的条件(a < b) implies (c <= d)。
如果一个double值使用比 a 更多的空间来表示long,那么由于鸽巢原理,没有映射可以满足您的初始约束。基本上,由于double类型可以表示比类型更多的不同值long,因此无法保留关系的严格偏序<,因为多个double值将被迫映射到相同的long值。
也可以看看: