简体   繁体   中英

possible loss of precision error when using Math.floor() in java

when i try to compile this program it shows the following error :

src (master)$ javac AmstrongNumber.java

AmstrongNumber.java:26: error: possible loss of precision length = Math.floor(Math.log10(input)) + 1; ^ required: int

found: double 1 error

can any one clarify what is loss of precision error in java ? but doesn't Math.floor() return a int value. when i use (int) type casting instead of Math.floor() it shows no errors thank you in advance.

 import java.util.Scanner;
 public class AmstrongNumber {

    public static void main(String[] args) {

      double input;
      int length;
      double copy;
      double output = 0.0;
      double modulus;


      Scanner stdin = new Scanner(System.in);
      System.out.print(" Enter a number : ");
      input = stdin.nextInt();


      // find number of digits in the input
      length = Math.floor(Math.log10(input)) + 1;
      System.out.println();
      System.out.println(" no. of digits in the number is : " + length);
      System.out.println();
      copy = input;

      for(int n = 0; n < length; n++ ) {
        modulus = copy % 10; // find the last digit of the number
        copy = (int) copy / 10; // discarding the last digit
        output = output + Math.pow(modulus, (double)length);
      }

      if((int)input == (int)output) 
         System.out.printf(" %d is a Amstrong number ", (int)input);
      else 
         System.out.printf(" %d is not a Amstrong number ", (int)input);

  }

}

but doesn't Math.floor() return a int value

No. See the documentation

static double floor(double a) Returns the largest (closest to positive infinity) double value that is less than or equal to the argument and is equal to a mathematical integer.

Yes, casting to an int is safe here, and will give you the result you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM