2

我在将 PHP 脚本移至 Java 时遇到问题。我正在使用谐波系列。我让它在 PHP 中工作,但是当我将它转换为 Java 时,它永远不会结束(无限循环)。有任何想法吗?或者甚至是更好的方法来完成它?

PHP:

<?php

$current = 0;
$num = 2.5;

while($current < $num) {
    for($i = 1; $current < $num; $i++) {
        $current = $current + (1 / $i);
    }

    // this ($current) will return "2.5928571428571" (which it should)
    echo $current;
}

?>

Java(Java 等价物,但未完成循环):

double current = 0;
double num = 2.5;
int i = 0;

while(current < num) {
    for(i = 1; current < num; i++) {
        current = current + (1 / i);
    }

    System.out.println(current);
}

或者也许我完全做错了:o。

4

5 回答 5

2

current never goes beyond 1 since 1/n=0 where n > 1.

A couple points:

  1. There should be no need to have the while loop or declare i outside the for loop
  2. use a double type
于 2012-05-17T03:55:07.277 回答
1

Use double numbers, not ints since int division will do funny things.

the fraction uses int literals, and int division must return an int, in your case it will often return 0 if i > 1

i.e.,

current = current + (1 / i); // will return current + 0 if i > 1

Better to make the numerator a double literal by changing 1 to 1.0:

current = current + (1.0 / i);

Now double division will do what you expect division should do.

于 2012-05-17T03:56:03.250 回答
0

int/int = int(如果结果是假设 .07 int 不能保存浮点数,它将为 0)所以

int/float = float(希望你得到)

于 2012-05-17T04:40:15.230 回答
0

问题在于类型转换。在这种情况下,PHP 不关心类型,所以它在那里工作。

另一方面,在 Java 中,您需要强制double分区上的类型才能正常工作。

double current = 0;
double num = 2.5;
int i = 0;

while(current < num) {
    for(i = 1; current < num; i++) {
        current += (1.0 / i); // Force the result to be a decimal with 1.0
    }
System.out.println(current);
}

或者,您可以从i一个double开始。

...
for(double i = 1.0; current < num; i+=1.0)
  current += 1.0/i;
于 2012-05-17T04:01:06.403 回答
0

创建一个中间变量只是为了查看总和是否是问题并能够调试。

double current = 0;
double num = 2.5;
double inc;

while(current < num) {
    for(int i = 1; current < num; i++) {
        inc = 1 / (double)i;
        current += inc;
    }
System.out.println(current);
}

如果它解决了您的问题,则最终代码可以是

double current = 0;
double num = 2.5;

while(current < num) {
    for(int i = 1; current < num; i++) {
        current += (1 / (double)i);
    }
System.out.println(current);
}
于 2012-05-17T04:01:09.353 回答