以下代码段是在不使用>
或<
条件运算符的情况下找到数字的符号(+/-)!
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!!
答案 0 :(得分:2)
您的代码中存在隐式转换。 这样:
n *= Double.NEGATIVE_INFINITY;
大致相当于:
n = (int) (n * Double.NEGATIVE_INFINITY);
n
在此代码段中为int
,Double.NEGATIVE_INFINITY
为double
,因此计算结果为double
。之后因为您将结果保存在int
变量中,结果会downcasted
到int
。 int
没有像无限的东西,所以你的双倍得到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接受了整数乘法的溢出。