简体   繁体   English

分析Java中的阶乘循环

[英]Analyzing factorial loop in Java

Consider the following code: 考虑以下代码:

int number;
double factorial = 1.0;

for(int i=2; i<=5; i++)
{
    factorial *=i;
    System.out.println(number + "! = " + factorial );
}

Why is the output 为什么输出

2.0
6.0
24.0
120.0

I know it starts from 2 until 5. 我知道它从2开始到5。

factorial *=i; 

means factorial =i*factorial; 表示阶乘= i *阶乘;

factoial variable scope is relay outside of loop so it it not reset on every loop iteration 工厂变量范围是循环外的中继,因此它不会在每次循环迭代时重置

so when i=2 that time factorial = 2.0 所以当i = 2时,时间阶乘= 2.0

when i=3 that time factorial value is 2.0 calculated above so factorial = 2.0*3 ie 6 当i = 3时,时间阶乘值为2.0,因此阶乘= 2.0 * 3即6

when i=4 that time factorial = 6*4 =24.0 当i = 4时时间阶乘= 6 * 4 = 24.0

when i=5 that time factorial = 24*5 = 120.0 当i = 5时,时间阶乘= 24 * 5 = 120.0

factorial *= i;

is equivalent to : 等效于:

factorial = factorial * i;

Let's say factorial is 1.0 and i is 2 : 假设factorial1.0i2

Well the calculus will be : 那么微积分将是:

factorial = 1.0 * 2

And so on til the end of the loop. 以此类推,直到循环结束。

I think you wanted to use a long (not a double and it's because you use a double that you get a floating-point type). 我认为您想使用long (而不是double ,这是因为使用double精度数会得到浮点类型)。 Factorial is usually of integral type. 阶乘通常是整数类型。 Something like, 就像是,

long factorial = 1;
for (int i = 2; i <= 5; i++) {
    factorial *= i;
    System.out.println(i + "! = " + factorial);
}

And I get (the expected) 我得到(预期的)

2! = 2
3! = 6
4! = 24
5! = 120
int number;


for(int i=2; i<=5; i++)
{
  double factorial = 1.0;
  factorial *=i;
  System.out.println(number + "! = " + factorial );
}

The code above will give output 2.0, 3.0 ... because with every iteration in loop new variable 'factorial' will be created and initialized to 1.0 上面的代码将提供输出2.0、3.0 ...,因为每次循环迭代时,都会创建新变量'factorial'并将其初始化为1.0

but with 但随着

int number;
double factorial = 1.0;

for(int i=2; i<=5; i++)
{
factorial *=i;
System.out.println(number + "! = " + factorial );
}

for i=2 对于我= 2

factorial = factorial *i // ie. 阶乘=阶乘* i // // 1.0 *2 = 2.0; 1.0 * 2 = 2.0; new value of factorial is 2.0 ie. 阶乘的新值是2.0,即。 factorial = 2.0 阶乘= 2.0

for i=3 对于我= 3

factorial = factorial *3 // ie. 阶乘=阶乘* 3 //即 2.0 * 3 =6.0 ; 2.0 * 3 = 6.0; which is factorial (when i=1) times 3 阶乘(当i = 1时)乘以3

for i=4 对于我= 4

factorial = factorial(when i=2) * 4 // ie. 阶乘=阶乘(当i = 2时* 4)//即。 6.0 *4 = 24.0 6.0 * 4 = 24.0

  • 1*2 = 2 1 * 2 = 2
  • 2*3 = 6 2 * 3 = 6
  • 6*4 = 24 6 * 4 = 24
  • 24*5 = 120 24 * 5 = 120

I guess, the output is right only 我猜,输出是正确的

1,2,6,24 are result stored in factorial var during prior iteration 1,2,6,24的结果在先前迭代期间存储在阶乘var中

2,3,4,5 are for loop i value 2,3,4,5用于循环i值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM