我刚才做了一个题目,但是不知道哪里错误,为什么结果总是1?
package edu.jmi.Chapter6;import java.math.BigInteger;
import java.util.Scanner;public class Test2 { /**
* 求1!+2!+3!+4!+.....+n!的值,从这个角度开始考虑:n!=(n-1)*n;??
*
* 没有考虑到他的范围的问题,这里的取值范围选择 long 还是bigInteger(String类型)
*/
//由于最后的结果需要放到bigInteger中,因此需要放回一个对象
public BigInteger bigInteger(int n){
//必须new一个对象为sum,
if(n<0){
System.out.println("请输入非负整数:");
return new BigInteger("-1"); //这个方面没有考虑到有返回值的情况
}else if(n ==0){
//由于使用bigInteger类型,所以需要将结果返回放到bigInteger中
return new BigInteger("1");
}else{
//递归公式的运用
BigInteger num = new BigInteger(String.valueOf(n));
return bigInteger(n-1).multiply(num); //这里只能通过对象乘以对象的方式进行运算?
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("请输入n的值:");
int n = sc.nextInt();
//BigInteger这个是大数据类
BigInteger sum = new BigInteger("1");//代表0的情况
Test2 t2 = new Test2();
for(int i = n;i>=1;i--){
sum.add(t2.bigInteger(i));
}
System.out.println("最后的结果为:"+sum.toString());
}}
还有帮我看看思路是不是错误啦,此外,可以帮我补充一点有关这方面 的知识吗?
package edu.jmi.Chapter6;import java.math.BigInteger;
import java.util.Scanner;public class Test2 { /**
* 求1!+2!+3!+4!+.....+n!的值,从这个角度开始考虑:n!=(n-1)*n;??
*
* 没有考虑到他的范围的问题,这里的取值范围选择 long 还是bigInteger(String类型)
*/
//由于最后的结果需要放到bigInteger中,因此需要放回一个对象
public BigInteger bigInteger(int n){
//必须new一个对象为sum,
if(n<0){
System.out.println("请输入非负整数:");
return new BigInteger("-1"); //这个方面没有考虑到有返回值的情况
}else if(n ==0){
//由于使用bigInteger类型,所以需要将结果返回放到bigInteger中
return new BigInteger("1");
}else{
//递归公式的运用
BigInteger num = new BigInteger(String.valueOf(n));
return bigInteger(n-1).multiply(num); //这里只能通过对象乘以对象的方式进行运算?
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
System.out.println("请输入n的值:");
int n = sc.nextInt();
//BigInteger这个是大数据类
BigInteger sum = new BigInteger("1");//代表0的情况
Test2 t2 = new Test2();
for(int i = n;i>=1;i--){
sum.add(t2.bigInteger(i));
}
System.out.println("最后的结果为:"+sum.toString());
}}
还有帮我看看思路是不是错误啦,此外,可以帮我补充一点有关这方面 的知识吗?
return bigInteger(n-1).multiply(num); //这里只能通过对象乘以对象的方式进行运算?没看到你定义了num啊?建议修改为:
return bigInteger(n-1).multiply(n);
return bigInteger(n-1).multiply(num); //这里只能通过对象乘以对象的方式进行运算?