Home >Backend Development >C++ >Translate the following into Chinese: C program to convert decimal to binary decimal

Translate the following into Chinese: C program to convert decimal to binary decimal

王林
王林forward
2023-09-10 12:37:02852browse

Translate the following into Chinese: C program to convert decimal to binary decimal

Consider the following example to understand how to convert decimal to binary decimal in C programming language.

Example 1 - Convert 25 to binary.

Step 1 - 25 / 2 Remainder: 1, quotient: 12

Step 2 - 12 / 2 Remainder: 0, quotient: 6

Step 3 - 6 / 2 Remainder: 0, quotient: 3

Step 4 - 3 / 2 Remainder: 1, quotient: 1

Step 5 - 1 / 2 Remainder: 1, quotient: 0

Thus, the equivalent binary number is: 11001

Example 2 - Convert 0.7 to binary.

Step 1 - 0.7 * 2 = 1.4, integer part = 1

Step 2 - 0.4 * 2 = 0.8, integer part = 0

Step 3 - 0.8 * 2 = 1.6, integer part = 1

Step 4 - 0.6 * 2 = 1.2, integer part = 1

Step 5 - 0.2 * 2 = 0.4, integer part = 0

Step 6 - 0.4 * 2 = 0.8, integer part = 0

So, the equivalent binary number is: 0.101100

Step 3 - Finally, the binary value of the decimal number 25.7 is as follows:

11001 + 0.101100 = 1101.101100

Example

The following is a C program to convert a decimal decimal to a binary decimal:

Real-time demonstration

#include<stdio.h>
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<=6;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;
}

Output

When executed When executing the above program, the following results will be produced -

Enter any fractional decimal number: 5.7
Equivalent binary value: 101.101100

The above is the detailed content of Translate the following into Chinese: C program to convert decimal to binary decimal. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete