英文:
Java power of number calculation problem with big numbers
问题
我对Java还不熟悉,当我尝试在没有使用Math.pow方法的情况下找出一个数的幂时,我意识到答案不正确。我想知道为什么?
public class Main() {
int x = 1919;
int y = x*x*x*x;
public static void main(String[] args) {
System.out.println(y);
}
}
>输出:2043765249
但通常答案是:13561255518721
英文:
I am new to Java and when I was trying to find power of number without Math.pow method I realized the answer was not right. And I want to learn why?
public class Main() {
int x = 1919;
int y = x*x*x*x;
public static void main(String[] args) {
System.out.println(y);
}
}
>Output: 2043765249
But normally answer is: 13561255518721
答案1
得分: 3
你正在使用 int 类型来存储答案,导致发生数值溢出。
请使用 double、long 或 BigInteger 类型来存储 y
,这样你将得到正确的答案。
public class Main {
public static void main(String[] args) {
System.out.println(Math.pow(1919, 4));
System.out.println((double) 1919 * 1919 * 1919 * 1919);
}
}
两种输出结果相同。
英文:
You're using an int for the answer, you're getting a numeric overflow.
Use double or long or BigInteger for y
and you'll get the right answer.
public class Main {
public static void main(String[] args) {
System.out.println(Math.pow(1919, 4));
System.out.println((double) 1919*1919*1919*1919);
}
}
Outputs the same value.
答案2
得分: 3
如果您逐步进行,您会发现在某一时刻值变为负数,这是因为达到了 Integer.MAX_VALUE
,即 2^31 -1
int x = 1919;
int y = 1;
for (int i = 0; i < 4; i++) {
y *= x;
System.out.println(i + "> " + y);
}
0> 1919
1> 3682561
2> -1523100033
3> 2043765249
您可以使用更大的类型,如 double
或 BigInteger
double x = 1919;
double y = x * x * x * x;
System.out.println(y); // 1.3561255518721E13
BigInteger b = BigInteger.valueOf(1919).pow(4);
System.out.println(b); // 13561255518721
英文:
If you go step by step, you'll see that at a moment the value becomes negative, that's because you reach Integer.MAX_VALUE
which is 2^31 -1
int x = 1919;
int y = 1;
for (int i = 0; i < 4; i++) {
y *= x;
System.out.println(i + "> " + y);
}
0> 1919
1> 3682561
2> -1523100033
3> 2043765249
You may use a bigger type like double
or BigInteger
double x = 1919;
double y = x * x * x * x;
System.out.println(y); // 1.3561255518721E13
BigInteger b = BigInteger.valueOf(1919).pow(4);
System.out.println(b); // 13561255518721
答案3
得分: 0
使用 long
替代 int
public class Main{
public static void main(String[] args) {
long x = 1919;
long y = x*x*x*x;
System.out.println(y);
}
}
英文:
Use long
instead of int
public class Main{
public static void main(String[] args) {
long x = 1919;
long y = x*x*x*x;
System.out.println(y);
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论