java - 为什么下面的代码返回错误的答案?
问题描述
在这里,我比较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
不是阿姆斯壮数
解决方案
你正在覆盖你的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;
}
推荐阅读
- spring - 我在将 JSF Apache myfaces CDI 迁移到 Spring Boot 时遇到问题
- c - Visual Studio 系统找不到指定的文件
- mysql - 非常大的mysql插入查询需要生命周期才能执行
- python-3.x - Pyspark在driver(python3.5)和worker(python2.7)中有不同的版本
- bootstrap-4 - 垂直对齐中心 div 引导程序 4
- kotlin - if(true) 的 kotlin 简写版本
- javascript - 如何在引导模式中传递以 json 数组形式编码并存储在数据库中的图像
- java - Springboot javax.xml.ws.service Nullpointerexception 同时实例化它
- python - 处理来自看门狗的 OSError
- nginx - 使用 Nginx 进行 Jmeter 负载测试