这个程序基本上是用指数来计算和打印的。它正在接近正确的答案,但它继续循环,不打印在同一条线上。例如,对于600,它应该打印2^3*3*5^2,但继续打印2^3 (新行) 3^1 (新行) 5^2,重复。
更新:修复了重复问题,现在打印2^ 3 ^1 ^ 5^2,现在只需要正确打印。
import java.util.Scanner;
class Factoring {
int n;
void setN(int u) {
n = u;
}
int getN() {
return n;
}
void factorize() {
int cnt;
for (int i = 2; i <= n; i++) {
cnt = 0;
while (n%i == 0) {
cnt++;
n /= i;
}
if (cnt == 0)
continue;
System.out.println(i + "^" + cnt);
}
}
}
public class Hw10 {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Factoring myF = new Factoring();
int u;
System.out.print("Enter a number(1 or less to stop)");
u = in.nextInt();
while (u > 1) {
myF.setN(u);
myF.factorize();
System.out.print("Enter a number(1 or less to stop)");
u = in.nextInt();
}
System.out.print("bye");
}
}发布于 2014-04-06 01:33:59
在循环中需要一个标志来确定它是否是第一个因素
int cnt;
boolean isFirstFactor = true;
for (int i = 2; i <= n; i++) {
cnt = 0;
while (n%i == 0) {
cnt++;
n /= i;
}
if (cnt == 0)
continue;
if (isFirstFactor)
isFirstFactor = false;
else
System.out.print(" * ");
System.out.print(i + "^" + cnt);
}https://stackoverflow.com/questions/22888903
复制相似问题