变量赋值给另一个变量会改变(原始变量改变),第二个变量会改变吗?

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

does variable assigned to another variable changes( original variable changes ) does the second variable change?

问题

以下是您要求的翻译内容:

我制作了这段代码来计算 x^y,而不使用 math 类。我使用了一个变量 m,将其赋值为 x。当 x 在循环中改变其值时,变量 m 的值是否也会随之改变,因为它等于 x,还是保持与初始 x 相同?

package loops;

import java.util.Scanner;

public class XToPowerY {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        int y = sc.nextInt();
        int m = x;

        for (int i = 0; i <= y - 2; i++) {
            x = x * m;
        }
        System.out.println(x);
    }
}
英文:

I made this code to calculate x^y without using math class, I used a variable m which I put equal to x. When x changes its value in the loop, does the value of m also changes as it is equal to x or remains the same to initial x?

package loops;

import java.util.Scanner;

public class XToPowerY {

/**
 * @param args
 */
public static void main(String[] args) {
	Scanner sc = new Scanner(System.in);
	int x = sc.nextInt();
	int y = sc.nextInt();
	int m = x;

	for (int i = 0; i &lt;= y - 2; i++) {
		x = x * m;

	}
	System.out.println(x);
}

}

答案1

得分: 2

m保持在x的初始值。如果在你的for循环中包括m = x;,它会发生变化。然而,请记住,Java只对基本数据类型行为如此。

英文:

m stays at the initial value of x. It would change, if you would include m = x; in your for-loop. Remember however, that Java only behaves this way with primitives.

答案2

得分: 1

使用调试器有助于您的情况 / 通过几次点击回答您的问题。

m 保持其值,因为您仅存储了 x 的值,而不是引用。

英文:

Using a debugger helps in your case / answers your question with a few clicks.

m keeps it value, since you store only the value of x not the reference.

huangapple
  • 本文由 发表于 2020年10月11日 20:57:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/64304248.html
匿名

发表评论

匿名网友

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

确定