import java.io.InputStreamReader;
import java.io.BufferedReader;
/**
* Class RecDemo
* Description 用递归求数列:1,3,6,10,15,21.... 求第N项的值
* 基本思路第N项减掉第N-1项是一个等差数列,差值为1,f(n)=n+f(n-1)和阶乘的区别是f(n)=n*f(n-1)
* Company opendata
* Author:Chenlly
* Date: 2008-12-08
* Version 1.0
*/
public class RecDemo{
public RecDemo(){
//do something;
}
//从控制台输入数据
public int putDate(){
boolean bflag=false;
int intValue=0;
while(!bflag){
try{
InputStreamReader ir=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(ir);
String str=br.readLine();
intValue=Integer.parseInt(str);
if(intValue>0){
bflag=true;
}
}catch(NumberFormatException ex){
System.out.println("输入有误,请重新输入");
}catch (Exception ex){
ex.printStackTrace();
}
}
return intValue;
}
//递归函数,第n
public int totalSeq(int n){
if(n==1){
return 1;
}else{
return (n + totalSeq(n-1));
}
}
//主调函数
public static void main(String []args){
RecDemo rd=new RecDemo();
System.out.println("please Enter a number:");
int n=rd.putDate();
int value=rd.totalSeq(n);
System.out.println("the value is:"+value);
}
}
递归-求第N项的值
最新推荐文章于 2024-01-20 20:58:43 发布