给定一个整数n,为每个整数打印以下值:
代码:
def print_formatted(number):
for i in range(1,number + 1):
decimal = i
print (decimal," ",end='')
d = decimal
octal = ""
while d != 0:
r = d % 8
d = d // 8
rem = str(r)
octal = rem + octal
print (octal," ",end='')
d = decimal
hexadecimal = ""
while d != 0:
r = d % 16
d = d // 16
rem = str(r)
c = r - 9
if c > 0:
if c == 1:
rem = 'A'
elif c == 2:
rem = 'B'
elif c == 3:
rem = 'C'
elif c == 4:
rem = 'D'
elif c == 5:
rem = 'E'
elif c == 6:
rem = 'F'
hexadecimal = rem + hexadecimal
print (hexadecimal," ",end='')
d = decimal
binary = ""
while d != 0:
r = d % 2
d = d // 2
rem = str(r)
binary = rem + binary
print (binary)
if __name__ == '__main__':
n = int(input())
print_formatted(n)
你的输出(标准输出)
1 1 1 1
2 2 2 10
预期产出
' 0'在第二行应该归入最后一行'。基本上,二进制文件应该从右到左打印,最右边的位置是最长二进制文件的最后一个数字。
答案 0 :(得分:0)
十六进制,八进制和二进制值可以分别使用python函数hex()
,oct()
和bin()
从十进制转换。
format函数可以输出数字hex,oct和bin,具体取决于传递给它的参数。
所以你可以做类似
的事情def print_formatted(number):
# "": decimal
# x: hexadecimal
# o: octal
# b: binary
bases = ["", "x", "o", "b"]
numbers_formatted = [format(number, x).upper() for x in bases]
return " ".join(numbers_formatted)
用作
print(print_formatted(11))
输出
# 11 B 13 1011
您可以结帐https://docs.python.org/3.5/library/string.html#formatspec了解详情。
答案 1 :(得分:0)
您需要注意输出中的文本对齐方式。您也可以使用内置的python函数
def print_formatted(number):
width=len(str(bin(number)))-2
for i in range(1, number + 1):
print("%s %s %s %s" % (str(i).rjust(width, " "), str(oct(i))[2:].rjust(width, " "), hex(i)[2:].rjust(width, " ").upper(), bin(i)[2:].rjust(width, " ")))
使用十进制十六进制和Bin功能。将它们隐藏为字符串。修剪基本符号。用户调整文字对齐方式