我需要将浮点数转换为IEEE(浮点数由scanf给出,它必须来自scanf,否则它会掉落并出错),但我似乎无法让它工作。我尝试使用 argc 和 argv,它是正确的,但我的提交平台不接受它,因为我需要通过扫描获得浮点数。问题是由于我尝试使用扫描,它不会打印正确的位。
数字 10 的输出应为:
位:01000001001000000000000000000000
正弦: +
暴露: 3
尾数: 1.25000000
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char Byte;
int expoente;
char sinal;
float mant=1;
int vector[32];
int vectorCounter=0;
char number;
void escreve_IEEE(char sinal, int expoente, float mant)
{
printf ("sinal: %cn", sinal);
printf ("expoente: %dn", expoente);
printf ("mantissa: %.8fn", mant);
}
int expoenteBaseDois(int exp)
{
int result = 1;
int i = 0;
while (i < exp) {
result = 2 * result;
i++;
}
return result;
}
void conversion(Byte b[]) {
int i = 3;
int v;
int s;
while ( i >= 0) {
v = b[i];
s = 7;
while (s >= 0) {
vector[vectorCounter] = (v >> s) & 1;
vectorCounter++;
s--;
}
i--;
}
vectorCounter = 0;
if(vector[vectorCounter]==0) sinal='+';
else sinal='-';
vectorCounter++;
int exp = -127;
s = 7;
while (vectorCounter <= 8) {
exp = exp + vector[vectorCounter] * expoenteBaseDois(s);
s--;
vectorCounter++;
}
expoente = exp;
s = 1;
while (vectorCounter <= 31) {
mant = mant + vector[vectorCounter] * ( 1.0 / (expoenteBaseDois(s)));
s++;
vectorCounter++;
}
}
int main(int argc, char *argv[]) {
float num;
scanf("%f", &num);
number= *(char*)#
conversion((Byte *) &number);
vectorCounter=0;
printf("bits: ");
while(vectorCounter>=0 && vectorCounter<32)
{
printf("%d",vector[vectorCounter]);
vectorCounter++;
}
printf("n");
escreve_IEEE(sinal, expoente, mant);
return 0;
}
你可以修复你奇怪的代码,修改main的第一个指令:
float num;
scanf("%f", &num);
// number= *(char*)#
conversion((Byte *) &num);
在代码中,您将全局char
变量传递给转换函数,该函数需要 4
字节的浮点变量地址。然后,您的代码将调用未定义的行为。
输出将是:
test@Linux:~/Test Folder$ ./test
10
bits: 01000001001000000000000000000000
sinal: +
expoente: 3
mantissa: 1.25000000