[英]Loop counter to get factorial
I have been given the following Pseudocode snippet我得到了以下伪代码片段
Function number_function()
Initialise variables factorial, number
Initialise Boolean valid to false
Loop while not valid
Display “Please enter a positive integer greater than 0”
Input number
If number contains numeric characters
Convert number to integer
If number is a positive integer
Set valid to true
End if
End if
End loop
Loop for counter from number to 1
Calculate factorial = factorial x count
If count is not 1
Print count and format with multiply
Else
Print count and format with equals
End if
End loop
Print factorial
End function
I have written this section myself however I am not sure what it means and how to do the loop for counter from number to 1 could anyone help please?我自己写了这一部分,但是我不确定这意味着什么以及如何为从数字到 1 的计数器进行循环,有人可以帮忙吗?
my code so far到目前为止我的代码
def number_function():
factorial = 0
count = 1
number = 0
valid = False
while valid != True:
number = input("Please Enter a positive integer greater than 0 ")
if number.isnumeric():
number = int(number)
if number >= 0:
valid = True
You have to calculate the factorial and print each step of the calculs.您必须计算阶乘并打印计算的每一步。 I understand it this way:
我是这样理解的:
def number_function():
factorial = 0
count = 1
number = 0
valid = False
while valid != True:
number = input("Please Enter a positive integer greater than 0 ")
if number.isnumeric():
number = int(number)
if number >= 0:
valid = True
count = number
factorial = 1
while count >= 1:
factorial = factorial * count
if count != 1:
print (count, "*")
else:
print (count, "=")
count -= 1
print (factorial)
number_function()
Example output is:示例 output 是:
Please Enter a positive integer greater than 0 3
3 *
2 *
1 =
6
you would want to do something like this:你会想做这样的事情:
you will not need a count variable, because your number will be your counter.您将不需要计数变量,因为您的数字将是您的计数器。 i added the print lines at strategic points, so you can follow, what the program does.
我在战略点添加了打印线,这样您就可以了解程序的功能。 they are not neccessary and you can delete them afterwards.
它们不是必需的,您可以在之后删除它们。
while (number > 0): ## looping while number not reached 0
factorial = factorial * number
print (factorial)
number = number - 1 ## diminish counter variable
print (number)
print (factorial)
this will provide your loop.这将提供您的循环。 in its header it will test on the condition and then do your factorial equation, then diminish your number to be multiplied again, but smaller until it reaches zero.
在它的 header 中,它将测试条件,然后做你的阶乘方程,然后减少你的数字以再次相乘,但更小直到它达到零。
i don't quite understand, what is meant by the rest, maybe my english skills fail me.我不太明白,rest 是什么意思,也许我的英语水平让我失望。 ;)
;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.