题目如下:
分别用递归和非递归方法求下列n阶多项式对应于变量x的值。在main方法中实现输入输出。
---------------------
我遇到的麻烦是:
用同样的输入,从(3,3)开始(前数为x,后数为n),两个方法得到的输出就不相同了。而我也检查不出其中问题,所以想拜托各位大虾帮帮忙,检查一下啦~:) (3,3)的结果:递归法为63,非递归法为68。
---------------------
我的代码为:递归的:
import java.io.*;class Test_recursion
{
static int duoXiangShi(int x,int n)
{
switch(n)
{
case 0:
return 1;
case 1:
return x;
default:
return ((2*n-1)*x*duoXiangShi(x,n-1)-(n-1)*duoXiangShi(x,n-2))/n;
}
}
public static void main(String[] args)
{
int x=0,n=0;
try
{
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入底数:");
x=Integer.parseInt(br1.readLine());
System.out.print("请输入阶数");
n=Integer.parseInt(br1.readLine());
}
catch(IOException e){}
System.out.println("结果是:"+duoXiangShi(x,n));
}
}
--------------------
非递归的:import java.io.*;class Test_nonrecursive
{
static int jieChengShi(int x,int n)
{
switch(n)
{
case 0:
return 1;
case 1:
return x;
default:
int i=0,lownumber=1,highnumber=x,register=0;
for(i=2;i<=n;i++)
{
register=((2*n-1)*x*highnumber-(n-1)*lownumber)/n;
lownumber=highnumber;
highnumber=register;
}
return register;
}
}
public static void main(String[] args)
{
int x=0,n=0;
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入底数:");
x=Integer.parseInt(br.readLine());
System.out.print("请输入阶数:");
n=Integer.parseInt(br.readLine());
}catch(IOException e){}
System.out.println("结果是:"+jieChengShi(x,n));
}
}
分别用递归和非递归方法求下列n阶多项式对应于变量x的值。在main方法中实现输入输出。
---------------------
我遇到的麻烦是:
用同样的输入,从(3,3)开始(前数为x,后数为n),两个方法得到的输出就不相同了。而我也检查不出其中问题,所以想拜托各位大虾帮帮忙,检查一下啦~:) (3,3)的结果:递归法为63,非递归法为68。
---------------------
我的代码为:递归的:
import java.io.*;class Test_recursion
{
static int duoXiangShi(int x,int n)
{
switch(n)
{
case 0:
return 1;
case 1:
return x;
default:
return ((2*n-1)*x*duoXiangShi(x,n-1)-(n-1)*duoXiangShi(x,n-2))/n;
}
}
public static void main(String[] args)
{
int x=0,n=0;
try
{
BufferedReader br1=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入底数:");
x=Integer.parseInt(br1.readLine());
System.out.print("请输入阶数");
n=Integer.parseInt(br1.readLine());
}
catch(IOException e){}
System.out.println("结果是:"+duoXiangShi(x,n));
}
}
--------------------
非递归的:import java.io.*;class Test_nonrecursive
{
static int jieChengShi(int x,int n)
{
switch(n)
{
case 0:
return 1;
case 1:
return x;
default:
int i=0,lownumber=1,highnumber=x,register=0;
for(i=2;i<=n;i++)
{
register=((2*n-1)*x*highnumber-(n-1)*lownumber)/n;
lownumber=highnumber;
highnumber=register;
}
return register;
}
}
public static void main(String[] args)
{
int x=0,n=0;
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("请输入底数:");
x=Integer.parseInt(br.readLine());
System.out.print("请输入阶数:");
n=Integer.parseInt(br.readLine());
}catch(IOException e){}
System.out.println("结果是:"+jieChengShi(x,n));
}
}
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货