为什么这段代码:
String value = JOptionPane.showInputDialog("Enter x"); //Input = 100
int x = Integer.parseInt(value);
double result = 1;
for (int i = 1; i <= x; i++) //used variable "x" here
{
result += (x * 1.0) / fact(i);
x *= x;
}
public static int fact(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
与此不同的工作?
String value = JOptionPane.showInputDialog("Enter x"); //Input = 100
int x = Integer.parseInt(value);
double result = 1;
for (int i = 1; i <= 100; i++) //and here I used the value "100"
{
result += (x * 1.0) / fact(i);
x *= x;
}
public static int fact(int n) {
int fact = 1;
for (int i = 1; i <= n; i++) {
fact *= i;
}
return fact;
}
我做的唯一更改是使用值100
而不是在终止表达式中使用变量x
!
当我运行第一个代码时,我得到:
9.479341033333334E7
然而,对于第二个我总是得到
NaN
为什么?
答案 0 :(得分:2)
两个片段的区别在于:
for (int i = 1; i <= x; i++) {
VS
for (int i = 1; i <= 100; i++) {
在第一种情况下,x每次变得更大!最终,它会在x
overflows时停止并变为0,这比第二种情况要快得多。有关为何导致0而不是其他随机数的原因的解释,请参阅:Why does this multiplication integer overflow result in zero?
在第二种情况下,当i = 34
时,fact(n)
将返回0,因此双重除法为(0 * 1.0) /0
,结果为NaN
。添加到NaN
时,任何双倍都会变为NaN
,这就是第二个代码段导致NaN
的原因。请参阅:In Java, what does NaN mean?