java 使用快捷操作符执行操作的方式与常规操作符有什么不同吗?
我正在开发一个关于帕斯卡三角形的java程序。
这就是它的编码方式:
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();
}
它显示:
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
但是当我尝试将代码更改为:
for(int i = 0; i < 5; i++){
for(int j = 0, x = 1; j <= i; j++){
System.out.print(x + " ");
x *= (i - j) / (j + 1);
}
System.out.println();
}
并且您可能已经注意到,只有运算符更改为 *=,但结果是:
1
1 1
1 2 0
1 3 3 0
1 4 4 0 0
知道发生了什么吗?提前致谢!
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 1
But when I tried to change the code to:
for(int i = 0; i < 5; i++){
for(int j = 0, x = 1; 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 0
Any idea what must have happened? Thanks in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为您以错误的顺序使用整数运算。
与 相同
括号很重要。
(i - j) / (j + 1)
在大多数情况下不是整数,但 java 无论如何都会将其四舍五入为整数。按照您首先执行的方式,
乘法发生在除法之前,因此不会出现任何舍入错误。
It's because you're using integer arithmetic in the wrong order.
is the same as
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
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
in stead of
which you probably wanted.
看起来像整数除法与运算顺序。尝试添加一些括号,我认为您最终会得到相同的结果。比如说,如果将 2/3 除以整数,就会得到 0。因此,是否先进行一些乘法很重要。
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.