int main(){

    long double fraDecimal,fraBinary,bFractional = 0.0,dFractional,fraFactor=0.1;
    long int dIntegral,bIntegral=0;
    long int intFactor=1,remainder,temp,i;

    printf("Enter any fractional decimal number: ");
    scanf("%Lf",&fraDecimal);

    dIntegral = fraDecimal;
    dFractional =  fraDecimal - dIntegral;

    while(dIntegral!=0){
         remainder=dIntegral%2;
         bIntegral=bIntegral+remainder*intFactor;
         dIntegral=dIntegral/2;
         intFactor=intFactor*10;
    }

   for(i=1;i<=12;i++){

       dFractional = dFractional * 2;
       temp =  dFractional;

       bFractional = bFractional + fraFactor* temp;
       if(temp ==1)
             dFractional = dFractional - temp;

       fraFactor=fraFactor/10;
   }

   fraBinary =  bIntegral +  bFractional;
   printf("Equivalent binary value: %Lf",fraBinary);

   return 0;
}

最佳答案

代替这个:

printf("Equivalent binary value: %Lf",fraBinary);


试试这个:

printf("Equivalent binary value: %.12Lf", fraBinary);


另请注意,它并不总是正确显示最后一个数字。至少在我的机器上,其中long double是8个字节。看来这将long double的精度推到了极限。当然,this指出


53位有效位精度给出15至17的有效位
十进制数字精度

08-04 18:14