多项式f(x)=a(n)*x^n+a(n-1)*x^n-1+·····+a(1)*x+a(0) (n>=1)
用户通过赋予系数,x及n的取值,计算机可计算得到该多项式的取值。要求:
1)设计算法,使得所需计算的乘法次数最少
2)给出输入及输出界面
我想用递归实现的,但是想了半天不会最后是这样写的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Program re = new Program();
double m;
int n;
Console.WriteLine("请输入n的值:");
n = int.Parse(Console.ReadLine());
int[] a;
a = new int[n + 1];
Console.WriteLine("请对数组进行赋值:");
Console.WriteLine("数组的长度为{0}", a.Length);
for (int i = 0; i < n + 1; ++i)
{ Console.WriteLine("请对a[{0}]赋值", i);
a[i] = int.Parse(Console.ReadLine()); }
int x;
Console.WriteLine("请对x赋值");
x = int.Parse(Console.ReadLine());
m=re.method(a,n,x);
Console.WriteLine("多项式的值为:");
Console.WriteLine(m);
Console.ReadLine();
}
double method(int []a,int n,int x)
{
double f=0;
for (int i = 0; i < n + 1; i++)
{
f+=a[i] * (Math.Pow(x, i));
}
return (f);
} }
}
用户通过赋予系数,x及n的取值,计算机可计算得到该多项式的取值。要求:
1)设计算法,使得所需计算的乘法次数最少
2)给出输入及输出界面
我想用递归实现的,但是想了半天不会最后是这样写的:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args)
{
Program re = new Program();
double m;
int n;
Console.WriteLine("请输入n的值:");
n = int.Parse(Console.ReadLine());
int[] a;
a = new int[n + 1];
Console.WriteLine("请对数组进行赋值:");
Console.WriteLine("数组的长度为{0}", a.Length);
for (int i = 0; i < n + 1; ++i)
{ Console.WriteLine("请对a[{0}]赋值", i);
a[i] = int.Parse(Console.ReadLine()); }
int x;
Console.WriteLine("请对x赋值");
x = int.Parse(Console.ReadLine());
m=re.method(a,n,x);
Console.WriteLine("多项式的值为:");
Console.WriteLine(m);
Console.ReadLine();
}
double method(int []a,int n,int x)
{
double f=0;
for (int i = 0; i < n + 1; i++)
{
f+=a[i] * (Math.Pow(x, i));
}
return (f);
} }
}
{
if (n == 0)
return sum;
sum = sum + a * Math.Pow(x,n);
return f(sum,n-1,a,x); }是不是这样啊?
private double f(double sum,int n,int a,int x )
{
if (n == 0)
return sum;
sum = sum + a * Math.Pow(x,n);
return f(sum,n-1,a,x); }
{
double sum=0;
double a = 4;
if (n >= 1)
{
return a*n*(Math.Pow(x,n))+ test1(n - 1, x);
}
else
{
return sum;
}
}这个呢?
{
double xn = 1;
return a.Skip(1).Sum(an => an * (xn *= x)) + a[0];
}
总共做2(n-1)次乘法