我正在尝试编写一个读取 2 个正整数(m 和 n)的程序,然后仅使用 while 循环打印 m 的前 n 个正整数。这是原始问题用 Python 3.x 语言编写一个程序,读取两个正整数 m 和 n,并打印前 n 个是 m 倍数的正整数。代码的输出应如下所示:Type a positive integer for m: 9 Type a positive integer for n: 5 The first 5 positive integers multiples of 9 are:918273645所以到目前为止我已经做了:m = int(input("Type a integer for m: "))n = int(input("Type a integer for n: "))i = 1print()print("The first ",n,"positive integers multiples of ", m," are:")while i <= n: m = m * i print(m) i = i + 1我想了解如何解决这个问题,我意识到使用 for 或者如果这样做会更容易
2 回答

BIG阳
TA贡献1859条经验 获得超6个赞
你的问题在这一行
m = m * i
您正在缓存一个中间值,然后在下一次迭代中将其相乘,因此第一次乘以您的m但下一次迭代时,您将乘以前一个中间值而不是原始值,m
您可以将循环更改为:
while i <= n:
print(m * i) # you don't need to save the intermediate result, you can just print it
i = i + 1

莫回无
TA贡献1865条经验 获得超7个赞
Nullman 的 asnwer 是正确的,无论如何这里是您的代码更正,以防万一它可以帮助您更好地理解错误:
m = 9
n = 5
i = 1
print()
print("The first ",n,"positive integers multiples of ", m," are:")
while i <= n:
multiple = m * i
print(multiple)
i = i + 1
你不能使用if,但你确实可以使用for:
m = 9
n = 5
i = 1
print()
print("The first ",n,"positive integers multiples of ", m," are:")
for i in range(1, n + 1):
multiple = m * i
print(multiple)
i = i + 1
添加回答
举报
0/150
提交
取消