I am working on a java program concerning the pascal's triangle.
So this is how it is coded:
for(int i = 0; i < 5; i++){
for(int j = 0, x = 1; j <= i; j++){
System.out.print(x + " ");
x = x * (i - j) / (j + 1);
}
System.out.println();
}
and it shows:
1 1 1 1 2 1 1 3 3 1 1 4 6 4 1But when I tried to change the code to:
for(int i = 0; i < 5; i++){
for(int j = 0, x = 1;开发者_StackOverflow中文版 j <= i; j++){
System.out.print(x + " ");
x *= (i - j) / (j + 1);
}
System.out.println();
}
and as you may have noticed, only the operator has changed to *=, but the result is:
1
1 1 1 2 0 1 3 3 0 1 4 4 0 0Any idea what must have happened? Thanks in advance!
It's because you're using integer arithmetic in the wrong order.
x *= (i - j) / (j + 1);
is the same as
x = x * ((i - j) / (j + 1));
The brackets are important. (i - j) / (j + 1)
is in most cases not a whole number, but java rounds it to an integer anyway.
The way you did it first
x = x * (i - j) / (j + 1);
the multiplication happens before the division, so you don't get any rounding errors.
You switched the high precedence * for a low precedence *= resulting in
x = x * ((i - j) / (j + 1));
in stead of
x = (x * (i - j)) / (j + 1);
which you probably wanted.
Looks like integer division versus order of operations. Try adding some parenthesis and I think you will eventually achieve the same results. If you, say, divide 2/3 in integers, you get 0. So it matters if you do some multiplying first.
精彩评论