[英]How to use Python to convert an octal to a decimal
我有這個小小的家庭作業,我需要將十進制轉換為八進制,然后將八進制轉換為十進制。 我做了第一部分,無法弄清楚第二部分來挽救我的生命。 第一部分是這樣的:
decimal = int(input("Enter a decimal integer greater than 0: "))
print("Quotient Remainder Octal")
bstring = " "
while decimal > 0:
remainder = decimal % 8
decimal = decimal // 8
bstring = str(remainder) + bstring
print ("%5d%8d%12s" % (decimal, remainder, bstring))
print("The octal representation is", bstring)
我在這里閱讀了如何轉換它: Octal to Decimal ,但我不知道如何將其轉換為代碼。
從十進制到八進制:
oct(42) # '052'
八進制轉十進制
int('052', 8) # 42
如果要將八進制作為字符串返回,則可能需要將其包裝在str
。
def dec2base():
a = int(input('Enter decimal number: \t'))
d = int(input('Enter expected base: \t'))
b = ""
while a != 0:
x = '0123456789ABCDEF'
c = a % d
c1 = x[c]
b = str(c1) + b
a = int(a // d)
return (b)
def dec2base_R():
a = int(input('Enter start decimal number:\t'))
e = int(input('Enter end decimal number:\t'))
d = int(input('Enter expected base:\t'))
for i in range (a, e):
b = ""
while i != 0:
x = '0123456789ABCDEF'
c = i % d
c1 = x[c]
b = str(c1) + b
i = int(i // d)
return (b)
def todec():
c = int(input('Enter base of the number to convert to decimal:\t'))
a = (input('Then enter the number:\t ')).upper()
b = list(a)
s = 0
x = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
for pos, digit in enumerate(b[-1::-1]):
y = x.index(digit)
if int(y)/c >= 1:
print('Invalid input!!!')
break
s = (int(y) * (c**pos)) + s
return (s)
注意:如果有人需要,我也有 GUI 版本
def decimal_to_octal(num1):
new_list = []
while num1 >= 1:
num1 = num1/8
splited = str(num1).split('.')
num1 = int(splited[0])
appendednum = float('0.'+splited[1])*8
new_list.append(int(appendednum))
decimal_to_octal(num1)
return "your number in octal: "+''.join(str(v) for v in new_list[::-1])
print(decimal_to_octal(384))
我不是 Python 專家......但我寫了這個邏輯......它工作正常。
def octToDec(oct):
lenOct = str(oct)
le = len(lenOct)
octal = 0
for i in (range(le)):
octal = octal + int(lenOct[i])* pow(8, le-1)
le -= 1
print(octal)
octToDec(number)
def decimalToOctal(num1):
new_list = []
while num1 >= 1:
num1 = num1/8
splited = str(num1).split('.')
num1 = int(splited[0])
appendednum = float('0.' + splited[1])*8
new_list.append(int(appendednum))
decimalToOctal(num1)
return "your number in octal: " + ''.join(str(v) for v in new_list[::-1])
print(decimalToOctal(384))
一個更簡單的版本:
a = input("Enter a string of octal digits: ")
while a != 0:
de = str(int(a,8));
print("The integer value is", de);
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.