首页 > 解决方案 > 为什么下面的代码返回错误的答案?

问题描述

在这里,我比较ArmstrongNo & out都具有相同的值(371),但打印错误的语句。

public class ArmstrongNumber {

static int ArmstrongNo = 371;
static int sum = 0;

public static void main(String[] args) {
    // TODO Auto-generated method stub
    ArmstrongNumber am = new ArmstrongNumber();
    int out = am.Armstrong();
    System.out.println(out);
    if (ArmstrongNo == out)
        System.out.println("It is an Armstrong number");
    else
        System.out.println("Not an Armstrong number");

}

public int Armstrong() {

    int length = String.valueOf(ArmstrongNo).length();// To find the length of integer
    for (int x = 0; x < length; x++) {
        int i = ArmstrongNo % 10;
        int cube = i * i * i;
        sum += cube;

        ArmstrongNo = ArmstrongNo / 10;
    }
    return sum;
 }

}

输出:

371

不是阿姆斯壮数

标签: java

解决方案


你正在覆盖你的ArmstrongNo这里ArmstrongNo = ArmstrongNo / 10;

然后总和为 371 但 ArmstrongNo 为 0

编辑

这修复了您的代码(至少在功能上)

public int Armstrong() {
        int ArmstrongNoCopy = ArmstrongNo;
        int length = String.valueOf(ArmstrongNoCopy)
                .length();// To find the length of integer
        for (int x = 0; x < length; x++) {
            int i = ArmstrongNoCopy % 10;
            int cube = i * i * i;
            sum += cube;

            ArmstrongNoCopy = ArmstrongNoCopy / 10;
        }
        return sum;
    }

推荐阅读