c#编写一个控制台应用程序,计算

1+x-x^2/2!+x^3/3!-x^4/4!+...+(-1)^(n+1)*x^n/n!
要求精度为10^-8

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{
class Program
{
public static long GetFactorial(int n)
{
if (n == 0 || n == 1)
{
return 1;
}
else
{
return n * GetFactorial(n - 1);
}
}
//计算阶乘的函数
static void Main(string[] args)
{
Console.WriteLine("请输入n:");
int n = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("请输入x: ");
double x = Convert.ToDouble(Console.ReadLine());
double sum = 0;
for (int i = 1; i <= n; i++)
{
sum += Math.Pow(-1, i + 1) * Math.Pow(x, i) / GetFactorial(i);
}
Console.WriteLine(sum);
Console.ReadLine();
}
}
}
已经测试通过,希望可以帮到你
测试数据:当n=3,x=3时,sum=3
温馨提示:答案为网友推荐,仅供参考
第1个回答  2009-11-13
using System;

namespace CSharpConsoleApplication
{
class Computer
{
public static long GetN(int n) //求n阶
{
long count = 1;
for (int i = 2; i <= n; i++)
{
count *= i;
}
return count;
}

public static double Compute(double x, int n) //使用double,精度应该能达到10^-8
{
if (n == 0)
return 1;
else
return Math.Pow(-1, n + 1) * Math.Pow(x, n) / GetN(n) + Compute(x,n-1); //递归

}
}

class Program
{
static void Main(string[] args)
{
double d = Computer.Compute(1.3, 10);

Console.Out.WriteLine(d);
}
}
}
相似回答