当我尝试编译该程序时,它显示以下错误:

src(master)$ javac AmstrongNumber.java

AmstrongNumber.java:26:错误:可能会损失精度
          长度= Math.floor(Math.log10(input))+1;
                                                 ^
  要求:int

找到:双
1个错误

谁能澄清java中的精度损失是什么?
但Math.floor()不会返回int值。当我使用(int)类型转换而不是Math.floor()时
没有显示错误
先感谢您。

 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);

  }


}

最佳答案

但Math.floor()不返回int值


否。请参见documentation


  静态double楼(double a)返回最大值(最接近正数)
  无限)小于或等于参数的double值,并且
  等于一个数学整数。


是的,在这里强制转换为int是安全的,它将为您提供所需的结果。

09-05 19:03
查看更多