最终变量在不应改变的情况下发生了变化。

huangapple go评论76阅读模式
英文:

Final variable changing when it shouldn't be

问题

大部分代码来自讲师提供的模板。
基本上每次Assert运行任何函数(例如mult函数),第二次运行函数时,它都会使用从第一次运行函数返回的结果,而不是应该传入的数组U[]的原始值。

乘法函数:

static double[] mult(double a, double[] V) { // 数量积标量和向量
    double[] ans = V;
    // double[] ans = {1.0, 2.0, 3.0, 4.0};
    for (int i = 0; i < 4; i++) {
        ans[i] = V[i] * a;
    }
    System.out.print("mult = " + ans[0] + " " + ans[1] + " " + ans[2] + " " + ans[3] + "\n");
    return ans;
}

主方法:

public static void main(String[] args) {

    final double[] U = {1, 2, 3, 4};

    Assert(mult(2, U)[0] == 2.0);  // 返回 U = 2.0, 4.0, 6.0, 8.0
    Assert(mult(2, U)[1] == 4.0);  // 返回 U = 4.0, 6.0, 8.0, 10.0(应与上面相同)
    Assert(mult(2, U)[2] == 6.0);
    Assert(mult(2, U)[3] == 8.0);
}
英文:

Most of this code is from a template supplied by a lecturer.
Basically every time the Assert runs any function (for example the mult function) the second time, it uses the result returned from the first time the function was run instead of the original values of the array U[] which is supposed to be passed in.

The multiplication function:

`static double [] mult(double a, double [] V) { // multiplying scalar and vector
	double[] ans = V;
	//double [] ans = {1.0, 2.0, 3.0, 4.0};
	for(int i =0; i&lt;4; i++)
	{
		ans[i] = V[i]*a;
	}
	System.out.print(&quot;mult =&quot; + ans[0] +&quot; &quot; + ans[1] +&quot; &quot; + ans[2] +&quot; &quot; + ans[3] + &quot;\n&quot;);
    return ans;
}`

The main method:

public static void main(String[] args) {

	
	final double [] U = {1, 2, 3, 4}; 
	
	Assert(mult(2, U)[0] ==  2.0);  //returns U = 2.0, 4.0, 6.0, 8.0
	Assert(mult(2, U)[1] ==  4.0);  //returns U = 4.0, 6.0, 8.0, 10.0 (should return same as above)
	Assert(mult(2, U)[2] ==  6.0); 
	Assert(mult(2, U)[3] ==  8.0);

答案1

得分: 1

因为你赋值 double[] ans = V; 而不是像这样使用一个全新的数组:

double[] ans = new double[V.length];

你无意中使用了作为参数传入的数组作为结果数组,然后在后面改变了值(这是合法的,但是不正确的)。

final 关键字只会引用你声明的引用,例如:

final int[] a = { 1, 2, 3 };
a[2] = 5;

是完全合法的,你只是不能:

a = new int[]{ 3, 4, 5 }; // 由于标识符 a 上的 final 修饰符而导致编译错误。
英文:

It is because you assign double[] ans = V; instead of using a fresh array like this:

double[] ans = new double[V.length];

You unintentionally use the array you get as a parameter as result array, and later change the values (which is legal but false).

final only ever referes to the reference you declare, for instance:

final int[] a = { 1, 2, 3 };
a[2] = 5;

is perfectly legal, you just can't:

a = new int[]{ 3, 4, 5 }; // compile error due to final modifier on identifier a.

huangapple
  • 本文由 发表于 2020年9月29日 21:26:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/64120611.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定