在JAVA中确定正\负号时出错

时间:2014-03-06 12:39:41

标签: java

以下代码段是在不使用><条件运算符的情况下找到数字的符号(+/-)!

    Scanner s = new Scanner(System.in);
    int n = s.nextInt(); /**take user input /

    /* stretch user input to either of infinity  */
    n *= Double.NEGATIVE_INFINITY;

    /* compare the result now */
    if(n == Double.NEGATIVE_INFINITY)
    {
     System.out.println("number is positive ");
    }
    else if (n == Double.POSITIVE_INFINITY )
    {
        System.out.println("number is negative" );  
    }
    else
    {
        System.out.println("could not determine number type!!" );
    }

我甚至添加了

System.out.println("nmbr and negtive infinity is : "+n+" "+Double.NEGATIVE_INFINITY);

用户输入: - 12,显示:

/* Ideally it should be "Infinity -Infinity" according to me */
nmbr and negtive infinity is : 2147483647 -Infinity 

在进行乘法后查看结果值,但由于某种原因。我不会让nmbr等于任何无限值

2个问题:

  • 在进行int类型输入时,是否会在乘法时升级为double类型?

  • 上述逻辑有什么问题? ,我总是得到输出:

could not determine number type!!

5 个答案:

答案 0 :(得分:2)

您的代码中存在隐式转换。 这样:

n *= Double.NEGATIVE_INFINITY;

大致相当于:

n = (int) (n * Double.NEGATIVE_INFINITY);

n在此代码段中为intDouble.NEGATIVE_INFINITYdouble,因此计算结果为double。之后因为您将结果保存在int变量中,结果会downcastedintint没有像无限的东西,所以你的双倍得到cast到尽可能高的整数:Integer.MAX_VALUE == 2147483647
很明显,这个数字不是无穷大。

如果您将n更改为double,那么您的代码正在运行

答案 1 :(得分:2)

如果您只对int值感兴趣,请尝试此操作:

Scanner s = new Scanner(System.in);
int n = s.nextInt(); /**take user input */

if ((n >> 31) == 0) System.out.println("number is positive");
else System.out.println("number is negative");

或者对于(n>&gt;> 31)== 0你可以使用(x | 0x80000000)== 0

==更新== 如你的评论所述,你对双打感兴趣。同样的游戏:

Scanner s = new Scanner(System.in);
int n = s.nextInt(); /** take user input */

if (n * Double.NEGATIVE_INFINITY == Double.POSITIVE_INFINITY) System.out.println("number is negative");
else System.out.println("number is positive");

答案 2 :(得分:1)

如果您想确定没有<>的号码的符号,可以阅读

Compute the sign of an integer - Bit Twiddling Hacks

将其改编为java,

public static boolean isPositive(int v) {
 return (((v != 0) ? 1 : 0 )| (v >> (Integer.SIZE - 1))) != -1;
}

注意:在此示例中,0被视为正面

答案 3 :(得分:1)

如果你不想搞乱一点算术,你可以简单地使用标准的Java API Integer.signum

int signum = Integer.signum(n);
if (signum == 0)
  //n is 0
else if (signum == -1)
  //n is negative
else //(signum == 1)
  //n is positive 

答案 4 :(得分:0)

n仍为int,32位。在比较中,n的被提升为double,并进行比较,这将始终为false。

介意,java接受了整数乘法的溢出。