ghostwwl
- UID
- 5349
- 帖子
- 12
- 积分
- 27
- 在线时间
- 10 分钟
|
1#
ghostwwl 发表于 2006-03-02 19:20
电脑报上的罗马数字问题!
本期电脑报上的请战贴:编程将大于0小于1000的阿拉伯数字转换为罗马数字。偶用python写的,代码如下:
[Copy to clipboard] [ - ]
CODE:
# coding:utf-8
class roma:
def __init__(self):
self.rdict={0: '', 1: 'I', 2: 'II', 3: 'III', 4: 'IV',
5: 'V', 6: 'VI', 7: 'VII', 8: 'VIII', 9: 'IX',
10: 'X', 400: 'CD', 20: 'XX', 900: 'CM',
30: 'XXX', 800: 'DCCC', 40: 'XL', 300: 'CCC',
50: 'L', 60: 'LX', 70: 'LXX', 200: 'CC', 80: 'LXXX',
600: 'DC', 90: 'XC', 100: 'XCC', 700: 'DCC',
500: 'D'}
def romac(self,num):
self.num=num
self.cnum=str(self.num)
if len(self.cnum)<2:
x=int(self.cnum[:1])
print "number %d is: %s" %(num,self.rdict[x])
elif len(self.cnum)<3:
x=int(self.cnum[:1])
y=int(self.cnum[1:2])
print "number %d is: %s" %(num,self.rdict[x*10]+self.rdict[y])
elif len(self.cnum)<4:
x=int(self.cnum[:1])
y=int(self.cnum[1:2])
z=int(self.cnum[2:3])
print "number %d is: %s" %(num,self.rdict[x*100]+self.rdict[y*10]+self.rdict[z])
elif len(self.cnum):
print "你输入的数字超出转换范围!"
def listall(self):
for a in range(0,1000,100):
for b in range(0,100,10):
for c in range(0,10):
print "the %d is: %s" %(a+b+c,self.rdict[a]+self.rdict[b]+self.rdict[c])
def main():
print """
要转换0~1000的罗马数字输入zhuan,
要列出0~1000的数字对照表输入list:
"""
number=roma()
menu=raw_input('输入zhuan或者list:')
if menu=='zhuan':
n=int(raw_input('Please in put a number:'))
number.romac(n)
elif menu=='list':
number.listall()
else:
print "请确认你输入的是zhuan或者list!"
if __name__=="__main__":
main()
运行结果如下:
要转换0~1000的罗马数字输入zhuan,
要列出0~1000的数字对照表输入list:
输入zhuan或者list:zhuan
Please input a number:38
number 38 is: XXXVIII
===========================
要转换0~1000的罗马数字输入zhuan,
要列出0~1000的数字对照表输入list:
输入zhuan或者list:zhu
请确认你输入的是zhuan或者list!
===========================
要转换0~1000的罗马数字输入zhuan,
要列出0~1000的数字对照表输入list:
输入zhuan或者list:zhuan
Please input a number:1111
你输入的数字超出转换范围!
===========================
要转换0~1000的罗马数字输入zhuan,
要列出0~1000的数字对照表输入list:
输入zhuan或者list:list
the 0 is:
the 1 is: I
the 2 is: II
the 3 is: III
the 4 is: IV
the 5 is: V
the 6 is: VI
the 7 is: VII
the 8 is: VIII
the 9 is: IX
the 10 is: X
the 11 is: XI
the 12 is: XII
the 13 is: XIII
|