C语言中的浮点数

xpcnnkqh  于 2023-10-15  发布在  其他
关注(0)|答案(1)|浏览(117)

我正在尝试做一些像下面这样的事情

#include <stdio.h>

int main() {
    float a = 0b00000100;
    float b = 0b0.0110; // this line is not working
    printf("The value of fist float is = %f\n", a*15);
    printf("The value of second float is = %f\n", b);
    return 0;
}

这里我唯一的目标是给B分配一个分数二进制数,它是0.0110,结果应该是0.375。有人知道吗?

kr98yfug

kr98yfug1#

我很快写了这个代码:

#include<stdio.h>
#include<string.h>

float binary_f(char fraction[]){
  char *pointp; //pointer to the point
  long integer=strtol(fraction, &pointp, 2); //Gives the integer and the pointer to the point, at the same time!
  int point=(int)(pointp-fraction);
  
  long div = 2;
  int lenght=strlen(fraction);
  float result=0;
  
  for (int i=point+1;i<lenght;i++){
    if (fraction[i]=='1'){
      result+=(float)1/div; 
    }
    div <<= 1; //Multiply the divisor by 2
  }
  return result+(float)integer;
}

int main() {
  char fractionary[]="10.001";
  float a=binary_f(fractionary);
  printf("%f",a);
  return 0;
}

图纸:

2.125000

正如您可能注意到的,它并不是真正健壮的,但它可以完成预期参数的工作。

相关问题