在 for 语句的终止表达式中使用数字文字有什么区别?
What's the difference when using numeric literal in termination expression of a for statement?
为什么这段代码:
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
为什么?
两个片段的区别是:
for (int i = 1; i <= x; i++) {
对比
for (int i = 1; i <= 100; i++) {
在第一种情况下,x 每次都会变大!最终,它会在 x
overflows and becomes 0, which will be much sooner than in the second case. For an explanation as to why this results in 0 instead of some other random number, see:
时停止
在第二种情况下,当i = 34
时,fact(n)
将return0,所以双除法是(0 * 1.0) /0
,结果是NaN
。将任何双精度添加到 NaN
时,都会变成 NaN
,这就是为什么第二个片段会导致 NaN
。参见:In Java, what does NaN mean?
为什么这段代码:
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
为什么?
两个片段的区别是:
for (int i = 1; i <= x; i++) {
对比
for (int i = 1; i <= 100; i++) {
在第一种情况下,x 每次都会变大!最终,它会在 x
overflows and becomes 0, which will be much sooner than in the second case. For an explanation as to why this results in 0 instead of some other random number, see:
在第二种情况下,当i = 34
时,fact(n)
将return0,所以双除法是(0 * 1.0) /0
,结果是NaN
。将任何双精度添加到 NaN
时,都会变成 NaN
,这就是为什么第二个片段会导致 NaN
。参见:In Java, what does NaN mean?