简体   繁体   中英

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.

factorial *=i; 

means factorial =i*factorial;

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

when i=3 that time factorial value is 2.0 calculated above so factorial = 2.0*3 ie 6

when i=4 that time factorial = 6*4 =24.0

when i=5 that time factorial = 24*5 = 120.0

factorial *= i;

is equivalent to :

factorial = factorial * i;

Let's say factorial is 1.0 and i is 2 :

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). 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

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

factorial = factorial *i // ie. 1.0 *2 = 2.0; new value of factorial is 2.0 ie. factorial = 2.0

for i=3

factorial = factorial *3 // ie. 2.0 * 3 =6.0 ; which is factorial (when i=1) times 3

for i=4

factorial = factorial(when i=2) * 4 // ie. 6.0 *4 = 24.0

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

I guess, the output is right only

1,2,6,24 are result stored in factorial var during prior iteration

2,3,4,5 are for loop i value

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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