回复 2楼 lz1091914999
我知道了,多谢大神指点,用数组做,在处理数据的时候很少会考虑会不会越界。
package MATH;
public class math {
public void calculate(int number){
int i=0;
int pArray[]=new int[100];
pArray[0]=1;
int count=1;
int flag=0;
for(int j=2;j<=number;j++){
for(i=0;i<count;i++){
pArray[i]*=j;
}
if (pArray[count - 1] >= 10 && pArray[count - 1] < 100) {
count++;
} else if (pArray[count - 1] >= 100 && pArray[count - 1] < 1000) {
count += 2;
}
for (i = 0; i < count; i++) {
if (pArray[i] >= 10 && pArray[i] < 100) {
flag = pArray[i] / 10;
pArray[i + 1] += flag;
pArray[i] = pArray[i] % 10;
} else if (pArray[i] >= 100 && pArray[i] < 1000) {
flag = pArray[i] / 100;
pArray[i + 2] += flag;
flag = (pArray[i] / 10) % 10;
pArray[i + 1] += flag;
pArray[i] = (pArray[i] % 100) % 10;
}
}
}
//print
for(i=count-1;i>=0;i--){
System.out.print(pArray[i]);
}
}
}
package MATH;
import java.util.Scanner;
public class test1 {
public static void main(String[] args) {
int number = 0;
int nFlag=1;
while(nFlag==1) {
System.out.print("你想计算几的阶乘:");
Scanner scanner = new Scanner(System.in);
number = scanner.nextInt();
math tst = new math();
System.out.print(number + "的阶乘是");
tst.calculate(number);
System.out.println();
System.out.print("是否继续(1:继续, 其他:退出):");
nFlag=scanner.nextInt();
}
}
}
这样就ok了!