为什么乘以正数会产生负值?
Why does multiplying positive numbers result in negative values?
对于某些输入,如 5、10、10,在 output.this 中有负值是一个程序,其中通过将相邻的 numbers.I 与 [=16= 相乘来创建一系列数字] 初学者,请帮我相应地修改我的代码。
import java.util.*;
public class Program
{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter first number");
int a=in.nextInt();
System.out.println("Enter the second number");
int b=in.nextInt();
System.out.println("Enter the no of terms");
int c=in.nextInt();
if(a>0 && b>0 && c>0)
{
for(int i=0; i<c+2; i++)
{
System.out.println(a + ",");
int mul=a*b;
a=b;
b=mul;
}
}
else
{
System.out.println("Invalid Input");
}
}
}
Enter first number
5
Enter the second number
10
Enter the no of terms
10
5,
10,
50,
500,
25000,
12500000,
-1032612608,
-975265792,
1931476992,
0,
0,
0,
每当 int
的值溢出时,它从另一端开始,即一旦您超过 int
可以容纳的最大值,它将从 [=14 的最小限制开始=].下溢也会发生同样的情况。检查以下程序以更好地理解它:
public class Program {
public static void main(String[] args) {
int x = Integer.MAX_VALUE;
int y = Integer.MIN_VALUE;
System.out.println(x);
System.out.println(x + 1);
System.out.println(y);
System.out.println(y - 1);
}
}
输出:
2147483647
-2147483648
-2147483648
2147483647
对于更大的整数计算,您应该使用 long
。对于更大的整数计算,您需要 BigInteger.
public class Program {
public static void main(String[] args) {
long x = Integer.MAX_VALUE + 1L;
long y = Integer.MIN_VALUE - 1L;
System.out.println(Integer.MAX_VALUE);
System.out.println(x);
System.out.println(Integer.MIN_VALUE);
System.out.println(y);
}
}
输出:
2147483647
2147483648
-2147483648
-2147483649
对于某些输入,如 5、10、10,在 output.this 中有负值是一个程序,其中通过将相邻的 numbers.I 与 [=16= 相乘来创建一系列数字] 初学者,请帮我相应地修改我的代码。
import java.util.*;
public class Program
{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
System.out.println("Enter first number");
int a=in.nextInt();
System.out.println("Enter the second number");
int b=in.nextInt();
System.out.println("Enter the no of terms");
int c=in.nextInt();
if(a>0 && b>0 && c>0)
{
for(int i=0; i<c+2; i++)
{
System.out.println(a + ",");
int mul=a*b;
a=b;
b=mul;
}
}
else
{
System.out.println("Invalid Input");
}
}
}
Enter first number
5
Enter the second number
10
Enter the no of terms
10
5,
10,
50,
500,
25000,
12500000,
-1032612608,
-975265792,
1931476992,
0,
0,
0,
每当 int
的值溢出时,它从另一端开始,即一旦您超过 int
可以容纳的最大值,它将从 [=14 的最小限制开始=].下溢也会发生同样的情况。检查以下程序以更好地理解它:
public class Program {
public static void main(String[] args) {
int x = Integer.MAX_VALUE;
int y = Integer.MIN_VALUE;
System.out.println(x);
System.out.println(x + 1);
System.out.println(y);
System.out.println(y - 1);
}
}
输出:
2147483647
-2147483648
-2147483648
2147483647
对于更大的整数计算,您应该使用 long
。对于更大的整数计算,您需要 BigInteger.
public class Program {
public static void main(String[] args) {
long x = Integer.MAX_VALUE + 1L;
long y = Integer.MIN_VALUE - 1L;
System.out.println(Integer.MAX_VALUE);
System.out.println(x);
System.out.println(Integer.MIN_VALUE);
System.out.println(y);
}
}
输出:
2147483647
2147483648
-2147483648
-2147483649