Error in determine positive\negative number in JAVA -
below snippet find sign(+/-) of number without using >
or <
conditional operators basically!
scanner s = new scanner(system.in); int n = s.nextint(); /**take user input / /* stretch user input either of infinity */ n *= double.negative_infinity; /* compare result */ if(n == double.negative_infinity) { system.out.println("number positive "); } else if (n == double.positive_infinity ) { system.out.println("number negative" ); } else { system.out.println("could not determine number type!!" ); }
i added
system.out.println("nmbr , negtive infinity : "+n+" "+double.negative_infinity);
for user input : -12, shows :
/* ideally should "infinity -infinity" according me */ nmbr , negtive infinity : 2147483647 -infinity
after doing multiplication see resultant value, reason. dont nmbr
equal infinite value
2 questions :
when taking
int
type input, getting promoteddouble
type on multiplication??whats wrong above logic?? , getting output :
could not determine number type!!
you have implicit cast in code. this:
n *= double.negative_infinity;
is equal to:
n = (int) (n * double.negative_infinity);
n
int
in code snippet, double.negative_infinity
double
, result of calculation double
. after because saving result in int
variable, result gets downcasted
int
. int
s not have infinity, double gets cast
ed highest possible integer: integer.max_value == 2147483647
.
it obvious number not infinity.
if change n double, code working
Comments
Post a Comment