The difference between "<" is less than the operator and "<=" when comparing large numbers using pow (x, y)

when I tried to compare the number 9223372036854775807 with Math.pow (2.63), it gave the wrong answer. Here is the code

long s = (long) (Math.pow(2, 63) - 1) ;
if ((s < Math.pow(2, 63)) && (s >= -Math.pow(2, 63)))
            System.out.println("* long");

it doesn't print anything, and when I do this,

long s = (long) (Math.pow(2, 63) - 1) ;
if ((s <= Math.pow(2, 63)) && (s >= -Math.pow(2, 63)))
            System.out.println("* long");

the actual program was this ...

package practice;

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Ques2ofHR_database {

public static void main(String[] args) {

    int i;
    Scanner in = new Scanner(System.in);
    int n = in.nextInt();
    for (i = 0; i < n; i++) {

        long s =0;
    try {
            s = in.nextLong();

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

            continue;
        }


    System.out.println(s + " can be fitted in:");
        if ((s < Math.pow(2, 7)) && (s >= -Math.pow(2, 7)))
            System.out.println("* byte");

        if ((s < Math.pow(2, 15)) && (s >= -Math.pow(2, 15)))
            System.out.println("* short");

        if ((s < Math.pow(2, 31)) && (s >= -Math.pow(2, 31)))
            System.out.println("* int");

        if ((s <= Math.pow(2, 63)) && (s >= -Math.pow(2, 63)))
            System.out.println("* long");

    }

    }

}

this program actually detects all data types that can store a given number (among bytes, short, int and long)

and thankx in advance ...

+4
source share
1 answer

It Long.MAX_VALUEtakes 64 bits to fit into a long variable.

Math.pow(2,63) double. (64) ( ), Math.pow(2,63) Long.MAX_VALUE, Long.MAX_VALUE t .

:

, Math.pow(2, 63) , 2 . , 1, , .

+1

Source: https://habr.com/ru/post/1599249/


All Articles