java - 阿姆斯特朗数java

标签 java

我在一些简单的代码上遇到了问题。我还没有看到我的代码问题出在哪里。当它应该返回 true 时,它会返回 false,因为 153 是一个阿姆斯特朗数。

以下是我的代码:

public class Armstrong {

   static double nArms, unidad, decena, centena, aux;


   Armstrong(){

   }

   Armstrong(double nArms){
      this.nArms = nArms;
   }

   public boolean esArmstrong(double nArms){

    aux = nArms % 100;
    centena = nArms / 100;
    decena = aux / 10;
    unidad = aux % 10;


    this.nArms = Math.pow(unidad, 3) + Math.pow(decena, 3) +Math.pow(centena, 3);

    if(this.nArms == nArms){
        return true;
    }else{
        return false;
    }
}



public static void main(String[] args) {

    Armstrong arms = new Armstrong();


    System.out.println(arms.esArmstrong(153));



}

}

最佳答案

当您打算进行整数算术时,您正在使用double。例如,当您编写

centena = nArms / 100;

您正在进行浮点除法(centena 被分配值1.53),但您想要执行整数除法。请改用 intlong(或 BigInteger)。

关于java - 阿姆斯特朗数java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25122452/

相关文章:

java - 不确定我正在使用继承/多态性问题吗?

java - 读取 Jetty 请求正文会导致 IndexOutOfBoundsException

java - 为现有类动态添加注解

java - LibGDX FreeTypeFontGenerator巨大字体消失字符

java - 所有属性都必须影响 JavaBean 的 hashcode() 和 equals() 方法吗?

java - Authorize.net Java 示例

java - 扫描 Java 中的类或 jar 文件

Java加载图像更快

java - 维护以前搜索的历史记录

java - 将 Paper 设置为 PageFormatter 不会更新 PageFormatter