【问题标题】:The result is coming back correct but not in correct format结果返回正确但格式不正确
【发布时间】:2017-11-28 07:23:15
【问题描述】:

我正在做一项作业,答案正确返回,但我需要他们说 5! = 120 而不仅仅是 = 120。我该怎么办?

def getInt():
    getInt = int
    done = False

    while not done:
        print("This program calcultes N!")

        # get input for "N
        N = int(input("Please enter a non-negative value for N: "))

        if N < 0:
            print("Non-Negative integers, please!")
        else:
            done = True
        return N

def main():
    n = getInt()

    for i in range(n-1):
        n = n * (i+1)

    print("=" ,n)

main()

【问题讨论】:

  • print(n_saved, '! = ', n, sep='')

标签: python-3.x while-loop range do-while sqrt


【解决方案1】:

你能告诉我你的作业指导吗? 我不确定您的示例中的第一个值是什么......当前迭代或输入的原始数字?

# declare getInt()
def getInt():

  getInt = int
  done = False

  while not done:

    # write "this program calculates N!"
    print("This program calcultes N!")

    # get input for "N
    N = int(input("Please enter a non-negative value for N: "))

    # if N < 0 then
    if N < 0:

      print("Non-Negative integers, please!")

    # else        
    else:

     # done = true
     done = True

    # return N
    return N

# main
def main():

  n = entry = getInt()

  for i in range(n-1):

    n = n * (i+1)

  print("{0}! = {1}".format(entry, n))

main()

结果:

/*
This program calcultes N!
Please enter a non-negative value for N: 5
5! = 120
*/

【讨论】:

  • 当我运行程序并输入 5 时它正在寻找阶乘,它会返回 120,这是 5 的阶乘,但我需要它的格式为“5!= 120”,你能告诉我如何你有5个! = 7200?
  • @KobeYazzie 我明白你的意思。更新了代码以显示这一点。
【解决方案2】:

我希望这段代码会有所帮助。 print('Enter a positive integer') a = int(input()) def factorial(n): if n == 0: return(1) if n == 1: return(1) if n > 1: return(n * factorial(n-1)) if a < 0: print('Non-Negative integers, please!') if a >= 0: print(str(a) + '! = ' + str(factorial(a)))

【讨论】:

    【解决方案3】:

    在for i in range(n-1)中,您可以使用另一个整数而不是 n,以确保事情不会搞砸,并且您可以像 joel 所说的那样打印print(i,"!=", n),但您将使用整数而不是 n。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 2012-04-11
      • 2016-02-06
      • 2017-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多