【问题标题】:How to count the amount of the printed numbers in an interval?如何计算一个区间内打印的数量?
【发布时间】:2020-11-20 12:45:03
【问题描述】:

我的代码看起来像这样,差不多完成了,只是我需要计算这些打印数字的数量,然后用它们打印出来。


start = int(input("Input the first number: "))
end = int(input("Input the last number: "))

 
for i in range(start,end):
  if i > 1:
    for j in range(2, i):
        if i % j==0 :
          break
    else:
      print(i)

输出:

2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97

问题是,我想打印出那里打印了多少个数字。感谢您的回答!

【问题讨论】:

    标签: python range primes intervals


    【解决方案1】:
    start = int(input("Input the first number: "))
    end = int(input("Input the last number: "))
    
    counter = 0  
      for i in range(start,end):
        if i > 1:
          for j in range(2, i):
              if i % j==0 :
                break
          else:
            print(i)
            counter = counter + 1
      print(counter)
    

    如果我知道这就是您要找的东西? 每次打印时,最后您想知道总共打印了多少次? 因此,当它要打印时,使用计数器来跟踪,然后在 for 循环完成时打印它。

    【讨论】:

      【解决方案2】:

      只需创建一个递增变量并在每次打印时递增它。然后在最后,打印那个变量。

      count = 0
      
      start = int(input("Input the first number: "))
      end = int(input("Input the last number: "))
      for i in range(start,end):
          if i > 1:
              for j in range(2, i):
                  if i % j == 0 :
                      break
              else:
                  count += 1
                  print(i)
                  
      print(f"Total numbers printed: {count}")
      

      【讨论】:

        猜你喜欢
        • 2022-12-28
        • 1970-01-01
        • 2020-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-12-17
        • 2020-11-27
        • 2013-02-01
        相关资源
        最近更新 更多