实现进制转化伪代码

实现进制转化伪代码

伪代码

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

其含义为:

  • 输入基数
  • 输入要转换的数字
  • 将商赋为1
  • 在商不为0的情况下,进入循环
    • 运算并记录要转换的数字与基数的整除的商
    • 运算并记录要转换的数字与基数的取余的余数
    • 让余数作为下一位留着作答案
    • 把要转换的数字设置成商,若不为0则进入循环,若不为0,则循环结束
  • 写答案

用python实现

#coding=utf-8

newBase = int(input("Enter the new base:"))
decimalNumber = int(input("Enter the number to be converted:"))
quotient = 1
a = {10:'A',11:'B',12:'C',13:'D',14:'E',15:'F'}   #创建字典对应十六进制
list_ = []          #创建空列表以装填余数

while quotient != 0:
    quotient = decimalNumber//newBase
    remainder = decimalNumber%newBase

    if remainder in a:
        remainder = a[remainder]
    list_.append(remainder)
    decimalNumber = quotient

list_.reverse()
print("The answer is")
for i in list_:
    print(i , end=" ")

运行结果如下(包括二进制、八进制与十六进制)

posted @ 2021-11-01 16:04  20211408王其  阅读(182)  评论(0编辑  收藏  举报