我正在解决在线法官的问题:https://acm.cs.nthu.edu.tw/problem/12237/
我需要用二进制表示来表示IEEE-754浮点数。
这是我的代码:
#include <stdio.h>
void binaryprint();
int main(){
float x;
while(scanf("%f",&x) != EOF){ //File end with EOF
unsigned int y = *(unsigned int*)&x;
if(x == 0){ // INput = 0 -> 0*32
for(int i = 0 ; i < 32 ; i++){
printf("%d",0);
}
}
else {
if(x > 0) printf("%d",0); //0 means positive but I find c will not print it out
binaryprint(y); //transfer to binary represent
}
printf("\n");
}
}
void binaryprint(unsigned int x){
if(x != 1){
binaryprint(x/2);
printf("%d",x%2);
}
else{
printf("%d",1);
}
}
但是我没有几个错误的答案,由于我不知道测试用例,我无法确定是否有任何例外导致错误的答案。感谢您的帮助!
这里是一些程序,带有注释的解释,可以处理所示的情况。 (它不处理无穷大或NaN。)
#include <math.h>
#include <stdio.h>
int main(void)
{
float x;
while (scanf("%f", &x) == 1)
{
// Print the sign bit.
putchar('0' + (x < 0));
if (x < 0)
x = -x;
/* Multiply or divide x by two to get a significand in the interval
[1, 2). At the same time, count the operations to figure what
power of two (in Exponent) is needed to scale that significand to
the original value of x.
*/
int Exponent = 0;
while (x < 1)
{
Exponent -= 1;
// If we reach the subnormal range, stop.
if (Exponent < -126)
break;
x *= 2;
}
while (2 <= x)
{
Exponent += 1;
x /= 2;
}
/* Encode the exponent by adding the bias of the IEEE-754 binary32
format.
*/
Exponent += 127;
// Print the seven bits of the exponent encoding.
for (int i = 7; 0 <= i; --i)
putchar('0' + (Exponent >> i & 1));
/* Skip the leading bit of the significand and print the 23 trailing
bits.
*/
x -= (int) x;
for (int i = 0; i < 23; ++i)
{
x *= 2;
int bit = x;
x -= bit;
putchar('0' + bit);
}
putchar('\n');
}
}