Ai
1 Star 0 Fork 0

dzc/Python-1

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
Decimal_To_Binary.py 1.50 KB
一键复制 编辑 原始数据 按行查看 历史
abhis2007 提交于 2019-10-02 19:29 +08:00 . Update Decimal_To_Binary.py
'''
PYTHON 3
Author: Sandeep Pillai (www.github.com/Corruption13)
Program: Decimal to Binary converter.
THis program accepts fractional values, the accuracy can be set below:
'''
decimal_accuracy = 7
def dtbconverter(num): # Function inputs a float value and returns a list as output
# Reasoning for list instead of integer: to avoid integer overflow error.
whole= [] # The part before decimal point
fractional = ['.'] # The part after decimal point
decimal = round(num%1, decimal_accuracy) # Extract fractional number part of decimal
w_num = int(num) # Extract whole number part of decimal.
i=0 # Some fractional decimal numbers have infinite binary values, so we limit this loop below.
#Loop to find binary of decimal part
while(decimal!=1 and i<decimal_accuracy):
decimal = decimal*2
fractional.append(int(decimal//1))
decimal = round(decimal%1, decimal_accuracy)
if(decimal == 0): break # Removes trailing zeros.
i = i + 1
#Loop to find binary of whole number part.
while(w_num!=0):
whole.append(w_num%2)
w_num = w_num//2
whole.reverse()
return whole + fractional ### End of dtbconverter() - 16 lines
#Test lines.
number = float(input("Enter Any base-10 Number: "))
print("The Binary Equivalant: " , *dtbconverter(number))
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
1
https://gitee.com/sdredboy/Python-1.git
git@gitee.com:sdredboy/Python-1.git
sdredboy
Python-1
Python-1
master

搜索帮助