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

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

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

问题

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

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

  1. package loops;
  2. import java.util.Scanner;
  3. public class XToPowerY {
  4. /**
  5. * @param args
  6. */
  7. public static void main(String[] args) {
  8. Scanner sc = new Scanner(System.in);
  9. int x = sc.nextInt();
  10. int y = sc.nextInt();
  11. int m = x;
  12. for (int i = 0; i <= y - 2; i++) {
  13. x = x * m;
  14. }
  15. System.out.println(x);
  16. }
  17. }
英文:

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?

  1. package loops;
  2. import java.util.Scanner;
  3. public class XToPowerY {
  4. /**
  5. * @param args
  6. */
  7. public static void main(String[] args) {
  8. Scanner sc = new Scanner(System.in);
  9. int x = sc.nextInt();
  10. int y = sc.nextInt();
  11. int m = x;
  12. for (int i = 0; i &lt;= y - 2; i++) {
  13. x = x * m;
  14. }
  15. System.out.println(x);
  16. }

}

答案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:

确定