打印小于给定最大值的某个数字的倍数

huangapple go评论149阅读模式
英文:

Print multiples of a number less than a given max

问题

打印小于m的n的倍数。

def print_multiples(n, max):
  while n <= max:
    a = range(n, (n*max)+1, n)
    print(*a)
        
print_multiples(4, 18)

因此,这个示例只会打印:

4
8
12
16

每个答案都在新的一行上。

英文:

Print multiples of n that are less than m.

def print_multiples(n, max):
  while n &lt;= max:
    a = range(n, (n*max)+1,n)
    print(*a)
        
print_multiples(4, 18)

so this example would only print

4
8
12
16

and each answer is on a new line.

答案1

得分: 0

这段代码将实现您想要的功能。它将最大数除以因子以获取最大的第二因子(//向下取整),然后加一,因为这是范围。然后它将遍历每个第二因子并打印出它们的倍数。

def print_multiples(n, m):
  for x in range(1, m//n + 1):
    print(x*n)

print_multiples(4, 18)

此外,您应该避免将max用作变量名,因为它是max()函数的关键字。

英文:

This code will do what you want. It divides the maximum number by the factor to get the maximum second factor (// rounds down) and then adds one because it is range. Then it will iterate through each of the second factors and print out the multiples.

def print_multiples(n, m):
  for x in range(1, m//n + 1):
    print(x*n)

print_multiples(4, 18)

Also, you should avoid using max as a variable name because it is a keyword for the max() function

huangapple
  • 本文由 发表于 2020年1月7日 00:15:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615440.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定