📜  将实数(0到1之间)转换为二进制字符串

📅  最后修改于: 2021-04-26 10:16:21             🧑  作者: Mango

给定介于0和1之间的实数(例如0.72)作为双精度值传递,请打印二进制表示形式。如果数字不能以最多32个字符的二进制形式准确表示,请打印“错误:”
例子:

Input :  (0.625)10
Output : (0.101)2

Input : (0.72)10
Output : ERROR

解决方案:首先,让我们先问自己二进制的非整数数字是什么样子。类似于十进制数字,二进制数字0 .101 2看起来像:

0. 101 2 = 1 * 1/2 1 + 0 * 1/2 2 +1 * 1/2 3

方法1:将小数部分乘以2

要打印小数部分,我们可以乘以2,然后检查2 * n是否大于或等于1。这实际上是“移动”分数和。那是:

r = 210 * n;
  = 210 * 0.1012;
  = 1 * 1/20 + 0 *1/21 + 1 * 1/22;
  = 1.012;

如果r> = 1,那么我们知道n在小数点后有1。通过连续执行此操作,我们可以检查每个数字。

C++
// C++ program to binary real number to string
#include 
#include
using namespace std;
  
// Function to convert Binary real
// number to String
string toBinary(double n)
{
    // Check if the number is Between 0 to 1 or Not
    if (n >= 1 || n <= 0)
        return "ERROR";
  
    string answer;
    double frac = 0.5;
    answer.append(".");
  
    // Setting a limit on length: 32 characters.         
    while (n > 0)
    {
          
        //Setting a limit on length: 32 characters     
        if (answer.length() >= 32)
                return "ERROR";
  
            // Multiply n by 2 to check it 1 or 0
            double b = n * 2;
            if (b >= 1)
            {
                answer.append("1");
                n = b - 1;
            }
            else
            {
                answer.append("0");
                n = b;
            }
        }
        return answer;
}
  
// Driver code
int main()
{
    // Input value 
    double n = 0.625; 
      
    string result = toBinary(n);
    cout<<"(0"<< result <<") in base 2"<


Java
// Java program to Binary real number to String.
import java.lang.*;
import java.io.*;
import java.util.*;
  
// Class Reperesentation of Binary real number
// to String
class BinaryToString
{
    // Main function to convert Binary real number
    // to String
    static String printBinary(double num)
    {
        // Check Number is Between 0 to 1 or Not
        if (num >= 1 || num <= 0)
            return "ERROR";
  
        StringBuilder binary = new StringBuilder();
        binary.append(".");
  
        while (num > 0)
        {
            /* Setting a limit on length: 32 characters,
               If the number cannot be represented
               accurately in binary with at most 32
               character  */
            if (binary.length() >= 32)
                return "ERROR";
  
            // Multiply by 2 in num to check it 1 or 0
            double r = num * 2;
            if (r >= 1)
            {
                binary.append(1);
                num = r - 1;
            }
            else
            {
                binary.append(0);
                num = r;
            }
        }
        return binary.toString();
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        double num1 = 0.625; // Input value in Decimal
        String output = printBinary(num1);
        System.out.println("(0" + output + ")  in base 2");
  
        double num2 = 0.72;
        output = printBinary(num2);
        System.out.println("(" + output + ") ");
    }
}


Python3
# Python3 program to binary real number to string
  
# Function to convert Binary real
# number to String
def toBinary(n):
  
    # Check if the number is Between 0 to 1 or Not
    if(n >= 1 or n <= 0):
        return "ERROR"
  
    answer = ""
    frac = 0.5
    answer = answer + "."
  
    # Setting a limit on length: 32 characters.
    while(n > 0):
  
        # Setting a limit on length: 32 characters
        if(len(answer) >= 32):
            return "ERROR"
  
        # Multiply n by 2 to check it 1 or 0
        b = n * 2
        if (b >= 1):
  
            answer = answer + "1"
            n = b - 1
  
        else:
            answer = answer + "0"
            n = b
  
    return answer
  
# Driver code
if __name__=='__main__':
    n = 0.625
    result = toBinary(n)
    print("(0", result, ") in base 2")
    m = 0.72
    result = toBinary(m)
    print("(", result, ")")
  
# This code is contributed by
# Sanjit_Prasad


C#
// C# program to Binary real number to String. 
  
using System;
using System.Text;
  
// Class Reperesentation of Binary real number 
// to String 
class BinaryToString 
{ 
    // Main function to convert Binary real number 
    // to String 
    static String printBinary(double num) 
    { 
        // Check Number is Between 0 to 1 or Not 
        if (num >= 1 || num <= 0) 
            return "ERROR"; 
  
        StringBuilder binary = new StringBuilder(); 
        binary.Append("."); 
  
        while (num > 0) 
        { 
            /* Setting a limit on length: 32 characters, 
            If the number cannot be represented 
            accurately in binary with at most 32 
            character */
            if (binary.Length >= 32) 
                return "ERROR"; 
  
            // Multiply by 2 in num to check it 1 or 0 
            double r = num * 2; 
            if (r >= 1) 
            { 
                binary.Append(1); 
                num = r - 1; 
            } 
            else
            { 
                binary.Append(0); 
                num = r; 
            } 
        } 
        return binary.ToString(); 
    } 
  
    // Driver Code 
    public static void Main() 
    { 
        double num1 = 0.625; // Input value in Decimal 
        String output = printBinary(num1); 
        Console.WriteLine("(0 " + output + ") in base 2"); 
  
        double num2 = 0.72; 
        output = printBinary(num2); 
    Console.WriteLine("(" + output + ") "); 
    } 
}


PHP
= 1 || $n <= 0)
        return "ERROR";
  
    $answer = "";
    $frac = 0.5;
    $answer .= ".";
  
    // Setting a limit on length: 32 characters.         
    while ($n > 0)
    {
          
        //Setting a limit on length: 32 characters 
        if (strlen($answer) >= 32)
                return "ERROR";
  
            // Multiply n by 2 to check it 1 or 0
            $b = $n * 2;
            if ($b >= 1)
            {
                $answer .= "1";
                $n = $b - 1;
            }
            else
            {
                $answer .= "0";
                $n = $b;
            }
        }
        return $answer;
}
  
// Driver code
  
// Input value 
$n = 0.625; 
  
$result = toBinary($n);
echo "(0" . $result . ") in base 2\n";
  
$m = 0.72;
$result= toBinary($m);
echo "(" . $result . ")";
      
// This code is contributed by mits
?>


C++
// C++ program to Binary real number to String.
#include 
#include
using namespace std;
  
// Function to convert Binary real
// number to String
string toBinary(double n)
{
    // Check if the number is Between 0 to 1 or Not
    if (n >= 1 || n <= 0)
        return "ERROR";
  
    string answer;
    double frac = 0.5;
    answer.append(".");
  
    // Setting a limit on length: 32 characters.         
    while (n > 0)
    {
        // 32 char max
        if (answer.length() >= 32)
            return "ERROR";
    // compare the number to .5
        if (n >= frac)
        {
            answer.append("1");
            n = n- frac;
        }
        else
        {
            answer.append("0");
        }
          
        frac /= 2;
    }
    return answer;
}
  
// Driver code
int main()
{
    // Input value 
    double n = 0.625;
      
    string result = toBinary(n);
    cout<<"(0"<< result <<") in base 2"<


Java
// Java program to Binary real number to String.
import java.lang.*;
import java.io.*;
import java.util.*;
  
// Class Reperesentation of Binary real number
// to String
class BinaryToString
{
    // Main function to convert Binary real
    // number to String
    static String printBinary(double num)
    {
        // Check Number is Between 0 to 1 or Not
        if (num >= 1 || num <= 0)
            return "ERROR";
  
        StringBuilder binary = new StringBuilder();
        double frac = 0.5;
        binary.append(".");
  
        while (num > 0)
        {
            /* Setting a limit on length: 32 characters,
               If the number cannot be represented
               accurately in binary with at most 32
               characters  */
            if (binary.length() >= 32)
                return "ERROR";
  
            // It compare the number to . 5.
            if (num >= frac)
            {
                binary.append(1);
                num -= frac;
            }
            else            
                binary.append(0);
  
            // Now it become 0.25
            frac /= 2;
        }
        return binary.toString();
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        double num1 = 0.625; // Input value in Decimal
        String output = printBinary(num1);
        System.out.println("(0" + output + ")  in base 2");
  
        double num2 = 0.72;
        output = printBinary(num2);
        System.out.println("(" + output + ") ");
    }
}


Python3
# Python3 program to Binary real number to String.
  
# Function to convert Binary real
# number to String
def toBinary(n):
  
    # Check if the number is Between 
    # 0 to 1 or Not
    if (n >= 1 or n <= 0):
        return "ERROR";
  
    frac = 0.5;
    answer = ".";
  
    # Setting a limit on length: 32 characters.     
    while (n > 0):
          
        # 32 char max
        if (len(answer) >= 32):
            return "ERROR";
              
        # compare the number to .5
        if (n >= frac):
            answer += "1";
            n = n - frac;
        else:
            answer += "0";
          
        frac = (frac / 2);
      
    return answer;
  
# Driver code
  
# Input value 
n = 0.625;
  
result = toBinary(n);
print("( 0", result, ") in base 2");
  
m = 0.72;
result = toBinary(m);
print("(", result, ")"); 
  
# This code is contributed 
# by mits


C#
// C# program to Binary real number to String. 
using System;
  
// Class Reperesentation of Binary 
// real number to String 
class BinaryToString 
{ 
    // Main function to convert Binary
    // real number to String 
    static string printBinary(double num) 
    { 
        // Check Number is Between 
        // 0 to 1 or Not 
        if (num >= 1 || num <= 0) 
            return "ERROR"; 
  
        string binary = ""; 
        double frac = 0.5; 
        binary += "."; 
  
        while (num > 0) 
        { 
            /* Setting a limit on length: 32 characters, 
            If the number cannot be represented 
            accurately in binary with at most 32 
            characters */
            if (binary.Length >= 32) 
                return "ERROR"; 
  
            // It compare the number to . 5. 
            if (num >= frac) 
            { 
                binary += "1"; 
                num -= frac; 
            } 
            else        
                binary += "0"; 
  
            // Now it become 0.25 
            frac /= 2; 
        } 
        return binary; 
    } 
  
    // Driver Code 
    public static void Main() 
    { 
        double num1 = 0.625; // Input value in Decimal 
        String output = printBinary(num1); 
        Console.WriteLine("(0" + output + ") in base 2"); 
  
        double num2 = 0.72; 
        output = printBinary(num2); 
        Console.WriteLine("(" + output + ") "); 
    } 
} 
  
// This code is contributed by mits


PHP
= 1 || $n <= 0)
        return "ERROR";
  
    $frac = 0.5;
    $answer = ".";
  
    // Setting a limit on length: 32 characters.         
    while ($n > 0)
    {
        // 32 char max
        if (strlen($answer) >= 32)
            return "ERROR";
              
        // compare the number to .5
        if ($n >= $frac)
        {
            $answer.="1";
            $n = $n - $frac;
        }
        else
        {
            $answer.="0";
        }
          
        $frac = ($frac / 2);
    }
    return $answer;
}
  
// Driver code
  
// Input value 
$n = 0.625;
  
$result = toBinary($n);
print("(0".$result.") in base 2\n");
  
$m = 0.72;
$result = toBinary($m);
print("(".$result.")"); 
  
// This code is contributed 
// by chandan_jnu
?>


输出:

(0.101)  in base 2
(ERROR) 

方法二

另外,我们也可以将数字与进行比较,而不是将数字乘以2并将其与1进行比较。 5,然后。 25,依此类推。下面的代码演示了这种方法。

C++

// C++ program to Binary real number to String.
#include 
#include
using namespace std;
  
// Function to convert Binary real
// number to String
string toBinary(double n)
{
    // Check if the number is Between 0 to 1 or Not
    if (n >= 1 || n <= 0)
        return "ERROR";
  
    string answer;
    double frac = 0.5;
    answer.append(".");
  
    // Setting a limit on length: 32 characters.         
    while (n > 0)
    {
        // 32 char max
        if (answer.length() >= 32)
            return "ERROR";
    // compare the number to .5
        if (n >= frac)
        {
            answer.append("1");
            n = n- frac;
        }
        else
        {
            answer.append("0");
        }
          
        frac /= 2;
    }
    return answer;
}
  
// Driver code
int main()
{
    // Input value 
    double n = 0.625;
      
    string result = toBinary(n);
    cout<<"(0"<< result <<") in base 2"<

Java

// Java program to Binary real number to String.
import java.lang.*;
import java.io.*;
import java.util.*;
  
// Class Reperesentation of Binary real number
// to String
class BinaryToString
{
    // Main function to convert Binary real
    // number to String
    static String printBinary(double num)
    {
        // Check Number is Between 0 to 1 or Not
        if (num >= 1 || num <= 0)
            return "ERROR";
  
        StringBuilder binary = new StringBuilder();
        double frac = 0.5;
        binary.append(".");
  
        while (num > 0)
        {
            /* Setting a limit on length: 32 characters,
               If the number cannot be represented
               accurately in binary with at most 32
               characters  */
            if (binary.length() >= 32)
                return "ERROR";
  
            // It compare the number to . 5.
            if (num >= frac)
            {
                binary.append(1);
                num -= frac;
            }
            else            
                binary.append(0);
  
            // Now it become 0.25
            frac /= 2;
        }
        return binary.toString();
    }
  
    // Driver Code
    public static void main(String[] args)
    {
        double num1 = 0.625; // Input value in Decimal
        String output = printBinary(num1);
        System.out.println("(0" + output + ")  in base 2");
  
        double num2 = 0.72;
        output = printBinary(num2);
        System.out.println("(" + output + ") ");
    }
}

Python3

# Python3 program to Binary real number to String.
  
# Function to convert Binary real
# number to String
def toBinary(n):
  
    # Check if the number is Between 
    # 0 to 1 or Not
    if (n >= 1 or n <= 0):
        return "ERROR";
  
    frac = 0.5;
    answer = ".";
  
    # Setting a limit on length: 32 characters.     
    while (n > 0):
          
        # 32 char max
        if (len(answer) >= 32):
            return "ERROR";
              
        # compare the number to .5
        if (n >= frac):
            answer += "1";
            n = n - frac;
        else:
            answer += "0";
          
        frac = (frac / 2);
      
    return answer;
  
# Driver code
  
# Input value 
n = 0.625;
  
result = toBinary(n);
print("( 0", result, ") in base 2");
  
m = 0.72;
result = toBinary(m);
print("(", result, ")"); 
  
# This code is contributed 
# by mits

C#

// C# program to Binary real number to String. 
using System;
  
// Class Reperesentation of Binary 
// real number to String 
class BinaryToString 
{ 
    // Main function to convert Binary
    // real number to String 
    static string printBinary(double num) 
    { 
        // Check Number is Between 
        // 0 to 1 or Not 
        if (num >= 1 || num <= 0) 
            return "ERROR"; 
  
        string binary = ""; 
        double frac = 0.5; 
        binary += "."; 
  
        while (num > 0) 
        { 
            /* Setting a limit on length: 32 characters, 
            If the number cannot be represented 
            accurately in binary with at most 32 
            characters */
            if (binary.Length >= 32) 
                return "ERROR"; 
  
            // It compare the number to . 5. 
            if (num >= frac) 
            { 
                binary += "1"; 
                num -= frac; 
            } 
            else        
                binary += "0"; 
  
            // Now it become 0.25 
            frac /= 2; 
        } 
        return binary; 
    } 
  
    // Driver Code 
    public static void Main() 
    { 
        double num1 = 0.625; // Input value in Decimal 
        String output = printBinary(num1); 
        Console.WriteLine("(0" + output + ") in base 2"); 
  
        double num2 = 0.72; 
        output = printBinary(num2); 
        Console.WriteLine("(" + output + ") "); 
    } 
} 
  
// This code is contributed by mits

的PHP

= 1 || $n <= 0)
        return "ERROR";
  
    $frac = 0.5;
    $answer = ".";
  
    // Setting a limit on length: 32 characters.         
    while ($n > 0)
    {
        // 32 char max
        if (strlen($answer) >= 32)
            return "ERROR";
              
        // compare the number to .5
        if ($n >= $frac)
        {
            $answer.="1";
            $n = $n - $frac;
        }
        else
        {
            $answer.="0";
        }
          
        $frac = ($frac / 2);
    }
    return $answer;
}
  
// Driver code
  
// Input value 
$n = 0.625;
  
$result = toBinary($n);
print("(0".$result.") in base 2\n");
  
$m = 0.72;
$result = toBinary($m);
print("(".$result.")"); 
  
// This code is contributed 
// by chandan_jnu
?>

输出:

(0.101)  in base 2
(ERROR)  

两种方法都同样好。选择最适合自己的一种。