用JAVA语言编程 求1!+2!+3!+4!+5!+6!+7!+8!+9!+10!一直到30
publicclassArrayPractise01{publicstaticvoidpuls(inttemp){intproccut=1;longsum[]=newlo...
public class ArrayPractise01 {
public static void puls(int temp){
int proccut = 1;
long sum[] = new long[temp];
long finalSum = 0;
while(temp>=1){
for (int j = 1; j <= temp; j++) {
proccut = proccut*j;
}
//System.out.println(temp+"的阶乘是:"+proccut);
sum[temp-1] = proccut;
proccut = 1;
temp--;
}
for (int i = 0; i < sum.length; i++) {
//System.out.println("sum["+i+"]:"+sum[i]+"\t");
finalSum = sum[i] + finalSum;
}
System.out.println("阶乘的和是:"+finalSum);
}
public static void main(String[] args) {
puls(30);
}
} 展开
public static void puls(int temp){
int proccut = 1;
long sum[] = new long[temp];
long finalSum = 0;
while(temp>=1){
for (int j = 1; j <= temp; j++) {
proccut = proccut*j;
}
//System.out.println(temp+"的阶乘是:"+proccut);
sum[temp-1] = proccut;
proccut = 1;
temp--;
}
for (int i = 0; i < sum.length; i++) {
//System.out.println("sum["+i+"]:"+sum[i]+"\t");
finalSum = sum[i] + finalSum;
}
System.out.println("阶乘的和是:"+finalSum);
}
public static void main(String[] args) {
puls(30);
}
} 展开
3个回答
展开全部
30!太大了,超过了int或者long的范围了。 需要用Java之中的BigInteger。
下面是替换后的程序,只是在你源程序上改的。
import java.math.BigInteger;
public class ArrayPractise01 {
public static void puls(int temp){
BigInteger proccut = BigInteger.ONE;
BigInteger sum[] = new BigInteger[temp];
BigInteger finalSum = BigInteger.ZERO;
while(temp>=1){
for (int j = 1; j <= temp; j++) {
BigInteger t = new BigInteger(Integer.toString(j));
proccut = proccut.multiply(t);
}
//System.out.println(temp+"的阶乘是:"+proccut);
sum[temp-1] = proccut;
proccut = BigInteger.ONE;
temp--;
}
for (int i = 0; i < sum.length; i++) {
//System.out.println("sum["+i+"]:"+sum[i]+"\t");
finalSum = finalSum.add(sum[i]);
}
System.out.println("阶乘的和是:"+finalSum);
}
public static void main(String[] args) {
puls(30);
}
}
下面是替换后的程序,只是在你源程序上改的。
import java.math.BigInteger;
public class ArrayPractise01 {
public static void puls(int temp){
BigInteger proccut = BigInteger.ONE;
BigInteger sum[] = new BigInteger[temp];
BigInteger finalSum = BigInteger.ZERO;
while(temp>=1){
for (int j = 1; j <= temp; j++) {
BigInteger t = new BigInteger(Integer.toString(j));
proccut = proccut.multiply(t);
}
//System.out.println(temp+"的阶乘是:"+proccut);
sum[temp-1] = proccut;
proccut = BigInteger.ONE;
temp--;
}
for (int i = 0; i < sum.length; i++) {
//System.out.println("sum["+i+"]:"+sum[i]+"\t");
finalSum = finalSum.add(sum[i]);
}
System.out.println("阶乘的和是:"+finalSum);
}
public static void main(String[] args) {
puls(30);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询
广告 您可能关注的内容 |