进制转化
作业要求
用Python或Scratch实现下面伪代码描述的进制转换程序,提交运行结果截图,至少三张,包含转换为二进制,八进制,十六进制的截图。
Write "Enter the new base"
Read newBase
Write "Enter the number to be converted"
Read decimalNumber
Set quotient to 1
WHILE (quotient is not zero)
Set quotient to decimalNumber DIV newBase
Set remainder to decimalNumber REM newBase
Make the remainder the next digit to the left in the answer
Set decimalNumber to quotient
Write "The answer is "
Write answer
转化代码
print("Enter the new base")
nb=int(input())
print("Enter the number to be converted")
dn=int(input())
q=1
answer=[]
while q!=0:
q=dn//nb
r=dn%nb
if r= =10:
i='A'
elif r= =11:
i='B'
elif r= =12:
i='C'
elif r= =13:
i='D'
elif r= =14:
i='E'
elif r= =15:
i='F'
else:
i=str(r)
answer+=i
dn=q
print("The answer is")
answer1=answer[::-1]
for k in answer1:
print(k,end="")
转化为python语言中遇到的问题
- 问题一
i运算完之后得到的为int类型,无法直接作为answer的元素 - 解决方案
用str函数,将int转为str - 问题二
输出的answer是倒过来的,怎么反向输出? - 解决方案
可以通过列表的自带定义[::-1]反向
或者使用函数reverse - 问题三
怎么让输出的列表变成数字 - 解决方案
用for语句,使元素逐个输出,并用end=“”,去掉enter