英文:
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 <= 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论