【问题标题】:How do I make a program that asks the user for a limit and如何制作一个要求用户提供限制和
【发布时间】:2018-08-15 21:49:07
【问题描述】:

我有这段代码询问用户限制,然后打印出小于或等于提供的限制的平方数序列。

n=int(input("Limit: "))
counter = 2
while counter <= n:
    a = counter*counter
    counter=a
    print(a)

这是我当前的代码,它应该像这样工作:

Max: 100
1
4
9
16
25
36
49
64
81
100

我卡住了,我该如何解决?谢谢!

【问题讨论】:

    标签: python-3.x numbers square-root


    【解决方案1】:

    首先,您需要将 counter 变量从 1 开始,否则您将无法将“1”作为平方值。

    就打印其余值而言,您需要做 3 件事:

    1. 检查计数器的平方是否小于限制。
    2. 如果超过限制,则打印 counter * counter 的结果。
    3. 将计数器递增 1

    将计数器增加 1,将允许您检查可能存在于指定限制以下的每个可能的正方形。下面的代码提供了一个简单的方法来完成这个匹配上面的伪代码:

    n=int(input("Limit: "))
    counter = 1
    while counter <= n:
        if counter * counter <= n:
            print(counter * counter)
        counter += 1
    

    如果您有任何问题,请告诉我,我很乐意澄清任何仍然没有意义的问题!

    【讨论】:

      【解决方案2】:

      您实际上并没有计算连续的平方。您应该找到counter 的平方,然后将counter 加一

      n=int(input("Limit: "))
      counter = 1
      sq = counter**2
      while sq <= n:
          print(sq)
          counter += 1
          sq = counter**2
      

      有趣的 itertools 解决方案:

      from itertools import accumulate, count, takewhile
      
      for i in takewhile(n.__gt__, accumulate(count(1, 2))):
          print(i)
      

      【讨论】:

        猜你喜欢
        • 2021-10-20
        • 1970-01-01
        • 2020-07-18
        • 1970-01-01
        • 1970-01-01
        • 2012-01-30
        • 2021-02-08
        • 1970-01-01
        • 2023-03-07
        相关资源
        最近更新 更多