gpt4 book ai didi

java - 为什么我的输入 -100000000000000 得到不正确的输出?

转载 作者:行者123 更新时间:2023-12-02 02:08:48 25 4
gpt4 key购买 nike

    public class dataType {

public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int t=sc.nextInt();

for(int i=0;i<t;i++)
{
try
{
long x=sc.nextLong();
System.out.println(x+" can be fitted in:");
if(x>=-128 && x<=127)System.out.println("* byte");
if(x>=-1*(int)(Math.pow(2,15)) && x<=(int)(Math.pow(2,15)-1))System.out.println("* short");
if(x>=-1*(int)(Math.pow(2,31)) && x<=(int)(Math.pow(2,31)-1))System.out.println("* int");
if((x>=-1*(int)(Math.pow(2,63))) &&( x<=(int)(Math.pow(2,63)-1)))
System.out.println("* long");


}
catch(Exception e)
{
System.out.println(sc.next()+" can't be fitted anywhere.");
sc.next();
}

}
}
}

For the Input number= -100000000000000, Expected Output = -100000000000000 can be fitted in: * long Actual Output = -100000000000000 can be fitted in:

Problem is that it is not printing the message after the last if condition to check whether the number is in range of long data type.

最佳答案

你的逻辑可能会变得乏味。使用 Wrapper 类方法,这样您就可以在不提供 then 范围本身的情况下工作。

例如:

Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int x = 0;
for(int i = 0; i <=t;i++) {
x = sc.nextInt();
try {
if(x >= BYTE.MINVALUE && x <= BYTE.MAXVALUE) System.out.println("Byte");
//Same format for all required datatypes

}
catch(Exception e) {
System.out.println(sc.next()+" can't be fitted anywhere.");
sc.next();
}
}

}

希望这有帮助!

关于java - 为什么我的输入 -100000000000000 得到不正确的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57340311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com