【发布时间】:2018-11-12 10:12:00
【问题描述】:
我正在编写一种方法来分解一个数字,由于某种原因,当我尝试打印 factorA 时,它说它无法识别,有什么建议吗?
public static void factorize(int n){
if (n % 2 == 0){ //If number is even
int factorA = 2;
int factorB = n/2;
}else{ //If number is odd
int halfLine = n/2; //Only variables that are even will be factors greater than half of them, this case is only for odd integers
int smallestFactorOdd = 3;
while (smallestFactorOdd < halfLine){ //Until you've found the smallest factor for add variables
if (n % smallestFactorOdd == 0){ //If smallestFactorOdd is a factor of n
int factorA = smallestFactorOdd;
int factorB = n/smallestFactorOdd;
}else{
smallestFactorOdd += 2;
}
}
}
System.out.println(factorA);
}
更新的代码(仍然收到错误):
public static void factorize(int n){
int factorA;
int factorB;
if (n % 2 == 0){ //If number is even
factorA = 2;
factorB = n/2;
}else{ //If number is odd
int halfLine = n/2; //Only variables that are even will be factors greater than half of them, this case is only for odd integers
int smallestFactorOdd = 3;
while (smallestFactorOdd < halfLine){ //Until you've found the smallest factor for add variables
if (n % smallestFactorOdd == 0){ //If smallestFactorOdd is a factor of n
factorA = smallestFactorOdd;
factorB = n/smallestFactorOdd;
}else{
smallestFactorOdd += 2;
}
}
}
System.out.println(factorA);
System.out.println(factorB);
}
【问题讨论】:
-
现在有什么新错误??还是同样的老错误??
-
提示:您想了解“范围界定”。在两个不同的子作用域中声明变量不会在封闭作用域中创建它!
-
错误表示变量可能尚未声明,我将研究范围