gpt4 book ai didi

java - 在 java 中使用 Math.floor() 时可能会出现精度错误

转载 作者:太空宇宙 更新时间:2023-11-04 06:22:15 25 4
gpt4 key购买 nike

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

src(主)$ javac AmstrongNumber.java

AmstrongNumber.java:26:错误:可能会丢失精度 长度 = Math.floor(Math.log10(输入)) + 1; ^ 必需:整数

发现:双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);

}

}

最佳答案

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

没有。请参阅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.

是的,转换为 int 在这里是安全的,并且会给你你想要的结果。

关于java - 在 java 中使用 Math.floor() 时可能会出现精度错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27288117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com