我想使用字符而不是像素在控制台中绘制一个圆圈,为此我需要知道每行中有多少像素。直径作为输入给出,您需要输出一个列表,其中包含图片每行的宽度(以像素为单位)
例如:
输入:7
输出:[3,5,7,7,7,5,3]
输入:12
输出:[4,8,10,10,12,12,12,12,10,10,8,4]
如何实施?
小智 3
这很好地提醒我在混合从零开始和从一开始的计算时要小心。在这种情况下,我必须考虑for循环是从零开始的,但直径除以 2 的商是从 1 开始的。否则,绘图将大于或小于 1。
顺便说一句,虽然我与您的答案相匹配7,但我没有为 给出完全相同的情节12:
注意- 使用 Python 3.9.6 进行测试
pixels_in_line = 0
pixels_per_line = []
diameter = int(input('Enter the diameter of the circle: '))
# You must account for the loops being zero-based, but the quotient of the diameter / 2 being
# one-based. If you use the exact radius, you will be short one column and one row.
offset_radius = (diameter / 2) - 0.5
for i in range(diameter):
for j in range(diameter):
x = i - offset_radius
y = j - offset_radius
if x * x + y * y <= offset_radius * offset_radius + 1:
print('*', end=' ')
pixels_in_line += 1
else:
print(' ', end=' ')
pixels_per_line.append(pixels_in_line)
pixels_in_line = 0
print()
print('The pixels per line are {0}.'.format(pixels_per_line))
Run Code Online (Sandbox Code Playgroud)
7 的输出:
Enter the diameter of the circle: 7
* * *
* * * * *
* * * * * * *
* * * * * * *
* * * * * * *
* * * * *
* * *
The pixels per line are [3, 5, 7, 7, 7, 5, 3].
Run Code Online (Sandbox Code Playgroud)
12 的输出:
Enter the diameter of the circle: 12
* *
* * * * * *
* * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * * * *
* * * * * * * * * *
* * * * * * * * * *
* * * * * * * *
* * * * * *
* *
The pixels per line are [2, 6, 8, 10, 10, 12, 12, 10, 10, 8, 6, 2].
Run Code Online (Sandbox Code Playgroud)