[英]Why is x *= (y1*y2*y3)/z1 not giving the same answer as x = x * (y1*y2*y3)/z1 in JAVA
I am solving this on Leetcode and I ran across this error while submitting the answer for the question.我在 Leetcode 上解决了这个问题,在提交问题的答案时遇到了这个错误。
ans *= (N-i+1)/i;
is not the same as ans = ans * (N-i+1)/i;
不等于
ans = ans * (N-i+1)/i;
The value of answer for each iteration m=51
and n=9
每次迭代
m=51
和n=9
的 answer 值
ans *= (N-i+1)/i;
ans *= (N-i+1)/i;
public int uniquePaths(int m, int n)
{
double ans = 1;
int N = m+n-2;
int R = Math.min(n, m)-1;
for(int i = 1; i <= R; i++)
{
ans *= (N-i+1)/i;
}
return (int)ans;
}
The output for that is: output 是:
51/1
ans=58.0
52/2
ans=1624.0
53/3
ans=29232.0
54/4
ans=380016.0
55/5
ans=3800160.0
56/6
ans=3.040128E7
57/7
ans=2.1280896E8
58/8
ans=1.27685376E9
ans = ans * (N-i+1)/i;
ans = ans * (N-i+1)/i;
public int uniquePaths(int m, int n)
{
double ans = 1;
int N = m+n-2;
int R = Math.min(n, m)-1;
for(int i = 1; i <= R; i++)
{
System.out.println((N-R+i)+"/"+i);
ans = ans * (N-i+1)/i;
System.out.println("ans="+ans);
}
return (int)ans;
}
51/1
ans=58.0
52/2
ans=1653.0
53/3
ans=30856.0
54/4
ans=424270.0
55/5
ans=4582116.0
56/6
ans=4.0475358E7
57/7
ans=3.00674088E8
58/8
ans=1.916797311E9
When the values being multiplied are the same, why am I getting two different answers?当相乘的值相同时,为什么我会得到两个不同的答案?
In ans *= (N-i+1)/i;
在
ans *= (N-i+1)/i;
, (N-i+1)/i
is evaluated first. ,
(N-i+1)/i
首先被评估。 All the operands are int
s, so integer division with truncation is performed.所有的操作数都是
int
s,所以执行了 integer 除法和截断。 The truncated result is then used to update the value of ans
.然后使用截断的结果来更新
ans
的值。
With ans = ans * (N-i+1)/i;
用
ans = ans * (N-i+1)/i;
, the first operand to the multiplication operator is a double
, so the result is a double. ,乘法运算符的第一个操作数是
double
,所以结果是 double 。 That result is divided by i
and floating-point division is performed.该结果除以
i
并执行浮点除法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.