[英]Compare 2 floats by their bitwise representation in C
我在考試中遇到了這個問題,我無法真正解決它,希望能得到一些幫助。
僅填空,當且僅當 x<y 時,function 必須返回 true。 假設 x,y 不能是 NaN(但可以是 +-inf) 不允許強制轉換,只使用 ux, uy, sx, sy
bool func(float x, float y) {
unsigned* uxp = ______________ ;
unsigned* uyp = ______________ ;
unsigned ux = *uxp;
unsigned uy = *uyp;
unsigned sx = (ux>>31);
unsigned sy = (uy>>31);
return ___________________________;
}
據推測,分配假設float
使用 IEEE-754 binary32 並且unsigned
是 32 位。
盡管某些 C 實現支持它,但使用unsigned
類型為float
對象命名是不合適的。 相反,您可以創建一個復合文字聯合,使用float
值初始化其float
成員,並訪問其unsigned
成員。 (C 標准支持,但 C++ 不支持。)
之后,只需根據符號位將比較分為幾種情況:
#include <stdbool.h>
bool func(float x, float y) {
unsigned* uxp = & (union { float f; unsigned u; }) {x} .u;
unsigned* uyp = & (union { float f; unsigned u; }) {y} .u;
unsigned ux = *uxp;
unsigned uy = *uyp;
unsigned sx = (ux>>31);
unsigned sy = (uy>>31);
return
sx && sy ? uy < ux : // Negative values are in "reverse" order.
sx && !sy ? (uy | ux) & 0x7fffffffu : // Negative x is always less than positive y except for x = -0 and y = +0.
!sx && sy ? 0 : // Positive x is never less than negative y.
ux < uy ; // Positive values are in "normal" order.
}
#include <stdio.h>
int main(void)
{
// Print expected values and function values for comparison.
printf("1, %d\n", func(+3, +4));
printf("1, %d\n", func(-3, +4));
printf("0, %d\n", func(+3, -4));
printf("0, %d\n", func(-3, -4));
printf("0, %d\n", func(+4, +3));
printf("1, %d\n", func(-4, +3));
printf("0, %d\n", func(+4, -3));
printf("1, %d\n", func(-4, -3));
}
樣品 output:
1, 1 1, 1 0, 0 0, 0 0, 0 1, 1 0, 0 1, 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.