猿问

读取 2 个正整数并仅使用“while”打印它的第一个倍数的程序

我正在尝试编写一个读取 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:

9

18

27

36

45

所以到目前为止我已经做了:


m = int(input("Type a integer for m: "))

n = int(input("Type a integer for n: "))

i = 1

print()

print("The first ",n,"positive integers multiples of ", m," are:")

while i <= n:

    m = m * i

    print(m)

    i = i + 1

我想了解如何解决这个问题,我意识到使用 for 或者如果这样做会更容易


呼唤远方
浏览 181回答 2
2回答

BIG阳

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

莫回无

Nullman 的 asnwer 是正确的,无论如何这里是您的代码更正,以防万一它可以帮助您更好地理解错误:m = 9n = 5i = 1print()print("The first ",n,"positive integers multiples of ", m," are:")while i <= n:&nbsp; &nbsp; multiple = m * i&nbsp; &nbsp; print(multiple)&nbsp; &nbsp; i = i + 1你不能使用if,但你确实可以使用for:m = 9n = 5i = 1print()print("The first ",n,"positive integers multiples of ", m," are:")for i in range(1, n + 1):&nbsp; &nbsp; multiple = m * i&nbsp; &nbsp; print(multiple)&nbsp; &nbsp; i = i + 1
随时随地看视频慕课网APP

相关分类

Python
我要回答