这是一个很经典的编程练习题:
如果一个正整数等于其各个数字的立方和,则称该数为阿姆斯特朗数(亦称为自恋数、自幂数)。
如 407 = 43 + 03 + 73 就是一个阿姆斯特朗数。
写一段代码,输出 1000 以内的所有阿姆斯特朗数。
附加题:输入一个正整数,输出距离它最近的阿姆斯特朗数。
期待各位同学提交解答。
提交代码可以使用 paste.ubuntu.com 或 codeshare.io 等代码分享网站,只需将代码复制上去保存,即可获得一个分享地址,非常方便。
往期问题可通过公众号菜单栏“课外辅导”栏目中进入查看。
【解答】美队盾牌
turtle 库相关介绍参见:【编程课堂】海龟作图
要注意的是,画图完成后需要调用 turtle.done(),否则程序就直接退出了。
给一份参考解答:
# coding=utf-8 import turtle import time import math def shield(): # 设置背景 turtle.bgcolor('#010101') # 设置速度 turtle.speed(10) # 依次填充同心圆 fill_circle('#FF0000', 230) fill_circle('#FFFFFF', 178) fill_circle('#FF0000', 129) fill_circle('#0000FF', 75) # 完成五角星 draw_five('#FFFFFF', 75) turtle.done() # 画圆线 def draw_circle(radium): turtle.home() turtle.penup() turtle.setheading(0) turtle.forward(radium) turtle.pendown() turtle.setheading(90) turtle.circle(radium) turtle.penup() turtle.home() # 填充圆环 def fill_circle(color, r1): turtle.color(color, color) turtle.fillcolor() turtle.begin_fill() draw_circle(r1) turtle.end_fill() # 画并填充五角星 def draw_five(color, radium): turtle.home() turtle.penup() turtle.setheading(90) turtle.forward(radium) turtle.setheading(288) turtle.pendown() long_side = (math.sin(math.radians(36))*radium)/math.sin(math.radians(126)) turtle.color(color, color) turtle.fillcolor() turtle.begin_fill() for i in range(10): turtle.forward(long_side) if i % 2 == 0: turtle.left(72) else: turtle.right(144) turtle.end_fill() turtle.penup() if __name__ == '__main__': shield()
推荐 @strawhat 同学的答案,思路清晰,程序中各部分功能独立,非常好理解:
http://pastebin.ubuntu.com/25147394/
同时也给出其他两位同学的答案:
@疯琴:
https://github.com/YngwieWang/python_practice/blob/master/AmericanCaptain.py
@xuxiaojiao:
http://pastebin.ubuntu.com/25160891/
『码上行动』在线学习班正在开放中,详情请回复 码上行动 查看
近期文章推荐阅读: