import java.util.Scanner;
class Factorial {
public static void main(String args[]) {
int n, c, fact = 1;
System.out.println("Enter an integer to calculate it's factorial");
Scanner in = new Scanner(System.in);
n = in.nextInt();
if ( n < 0 )
System.out.println("Number should be non-negative.");
else
{
for ( c = 1 ; c <= n ; c++ )
fact = fact*c;
System.out.println("Factorial of "+n+" is = "+fact);
}
}
}
对于这个用于查找数字阶乘的代码,我没有得到它所说的部分,&#34; fact = fact * c&#34;。 我知道这是因为事实得到了更新&#34;新的乘数因子为c,但数字是否相乘?
示例:n = 3且c = 1,2,3且fact = 1 ..那么过程看起来像,(1 * 1)*(1 * 2)*(1 * 3)= 6?
答案 0 :(得分:3)
表达式
fact = fact * c;
将fact
与c
相乘,并将结果存储在fact
中。
因此,在运行代码时会发生以下情况:
fact
为1
。1
,其结果为1
。2
并变为2
。3
并变为6
。4
并变为24
。等等。
答案 1 :(得分:0)
你是对的,它的工作原理如下:
fact is 1 initially
loop when c = 1:
multiply c with fact i.e. 1 * 1
store the result back in fact i.e. fact = 1
loop when c = 2
multiply c with fact i.e. 1 * 2
store the result back in fact i.e. fact = 2
loop when c = 3
multiply c with fact i.e. 2 * 3
store the result back in fact i.e. fact = 6