要求:输入一个-127到127之间的十进制整数x,输出一个8位的二进制整数
例如:输入x=-1,输出11111111;输入x=10,输出00001010
以下是本大一新生尽力写出的不完全代码:
x=int(input())
r=0
L=[]
while(x>0):
r=x%2
x=x//2
L=[r]+L
for i in range(0,len(L)):
print(L[i],end='')
看题意没有让写出原理吧,直接用字符串格式化输出就行吧
x=int(input())
r=0
L=[]
flag =0
if(x<-127 or x > 127):
print("wrong input")
else:
if(x>0):
print("{:0>8o}".format(x)) ## :0>8o 指的是把整型x以八进制输出, 其中o表示8进制,8表示输出8位位宽
elif(x<0 and x!= -1):
print("1{:0>7o}".format(abs(x))) ## 这个是输出7位位宽的八进制数,因为是负数,所以首位加1
else:
print("11111111")