,所以我的分配是在数字范围内找到所有"魔术数"(用户输入)。魔术数字是一个数字,其因子(本身除外)总结到该数字。所以6将是一个神奇的数字,因为它的因素是自身的1,2和3,总计为6。我已经盯着这个代码了一段时间,但我无法弄清楚为什么它不会打印出来魔术数字。任何帮助将不胜感激。
public class MagicNumber {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("What is the top of the range?");
int range = IO.readInt();
if (range <= 0 ) {
IO.reportBadInput();
}
int sumOfFactors = 0;
for (int i = 1 ; i <= range ; i++) {
for (int m = 1 ; m < i; m++) {
if (i % m == 0) {
sumOfFactors = sumOfFactors + m;
}
if (sumOfFactors == i) {
System.out.println(i);
}
}
}
}
}
您正在测试sumOfFactors == i
是否仍在求和因素。您需要在m
循环外移动。然后,您需要将sumOfFactors
设置为0,然后每次通过i
循环启动m
循环,而不仅仅是在循环开始时一次。
我我认为您需要在第一个for
循环中初始化int sumOfFactors = 0;
并移动第二个if
,从第二个for
循环中,因为您需要将总因子的总和与当前数字进行比较如下:
for (int i = 1 ; i <= range ; i++) {
int sumOfFactors = 0; //<--Moved inside
for (int m = 1 ; m < i; m++) {
if (i % m == 0) {
sumOfFactors = sumOfFactors + m;
}
}
if (sumOfFactors == i) { // <-- moveed out of second loop
System.out.println(i);
}
}
尝试以下:
public class MagicNumber {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.print("What is the top of the range?");
int range = IO.readInt();
if (range <= 0 ) {
IO.reportBadInput();
}
for (int i = 1 ; i <= range ; i++) {
int sumOfFactors = 0;
for (int m = 1 ; m < i; m++) {
if (i % m == 0) {
sumOfFactors = sumOfFactors + m;
}
}
if (sumOfFactors == i) {
System.out.println(i);
}
}
}
}
只是参考此魔术数字程序http://getProgramcode.com/2013/11/java-progmprogm-to-check-check-check-check-for-a-magic-number/和写作的想法这个。
public class HelloWorld{
public static void main(String []args){
static int number=5432;
while(number>9){
int tot = calculateSum(number);
System.out.println(tot);
}
}
private static int calculateSum(int num){
int sum = 0;
while (num > 0) {
int a = num % 10;
sum = sum+ a;
num = num / 10;
}
number = sum;
return sum;
}
}
public class Magic {
public static void main(String[] args) {
// TODO Auto-generated method stub
int b =778393;
int e=0,c;
while (b>=10) {
while (b>0) {
c=b%10;
b=b/10;
e=e+c;
}
b=e;
e=0;
System.out.println(b);
}
if (b==1) {
System.out.println("It is a magic no."+b);
} else {
System.out.println("Not"+b);
}
}
}