0

在函数fermatFactorization()中,a并且b作为参考参数传递,因为我使用的是LongClass。但是,在testFermatFactorization()我传递aand bto的函数中, andfermatFactorization()的值不会改变,因此会打印. 我通过打印 out和in对此进行了测试,得到了我期望的输出。abtestFermatFactorization()(0)(0)abfermatFactorization()

我在看什么?编译器是否可以更改ab因为fermatFactorization()它们只是被分配给?(怀疑)

public static void fermatFactorization(Long n, Long a, Long b)   
//PRE:  n is the integer to be factored
//POST: a and b will be the factors of n
{
    Long v = 1L;
    Long x = ((Double)Math.ceil(Math.sqrt(n))).longValue();
    //System.out.println("x: " + x);
    Long u = 2*x + 1;
    Long r = x*x - n;

    while(r != 0)                 //we are looking for the condition x^2 - y^2 - n to be zero
    {
        while(r>0)
        {
            r = r - v;            //update our condition
            v = v + 2;            //v keeps track of (y+1)^2 - y^2 = 2y+1, increase the "y"
        }
        while(r<0)
        {
            r = r + u;
            u = u + 2;            //keeps track of (x+1)^2 - x^2 = 2x+1, increases the "x"
        }
    }

    a = (u + v - 2)/2;            //remember what u and v equal; --> (2x+1 + 2y+1 - 2)/2 = x+y
    b = (u - v)/2;                //                             --> (2x+1 -(2y+1))/2 = x-y
}

public static void testFermatFactorization(Long number)
{
    Long a = 0L;
    Long b = 0L;
    fermatFactorization(number, a, b);
    System.out.printf("Fermat Factorization(%d) = (%d)(%d)\n", number, a, b);
}
4

4 回答 4

8

Java 是按值传递的。如果为参数分配一个新值,它不会影响调用者方法中的值。

你有两个选择:

  • 使您的方法返回a-b在一个int[]或使用具有两个字段的单独FactorizationRezult类中。这样,您将在被调用方法中声明ab作为局部变量,而不是将它们作为参数。这是最可取的方法。

  • 另一种方法是使用 aMutableLong并使用setValue(..)方法 - 这样更改将影响调用方方法中的对象。这是不太可取的

于 2012-10-02T21:15:06.770 回答
3

a 和 b 是引用,而不是“引用参数”,它们是按值传递的。这些值在被调用的方法中发生了更改,但这对调用者没有影响。

Java 中没有“按引用传递”。

于 2012-10-02T21:17:13.683 回答
1

在 Java 中,一切都是按值传递的。没有引用调用。即使你传递一个对象,它的引用也是按值传递的。因此,当您传递一个Long对象时,您只是通过值传递对它的引用。

Long,就像其他原始类型包装器一样,是“不可变的”。您无法更改其内部的 long 值。因此,如果您不想更改设计,则必须自己(或使用MutableLong)长时间制作一个可变包装器并将其传递。如果您问我,更改您的设计以返回结果而不是更改方法参数是一种更好的方法。

于 2012-10-02T21:19:46.540 回答
0

使用 = 运算符清除内存中存储局部变量的位置并替换它。这不会影响原始变量。按值传递仅允许您修改对象中的数据(例如修改其中的字段),而不是实际引用。

于 2012-10-02T21:15:17.273 回答