//创建控制台应用 利用公式计算q的近似值,并运行出k=10的q的值
using System;
public class Calculation
{
public double result = 1;
private int k;
public Calculation(int k)
{
this.k = k;
}
public double GetResult(int k)
{
if (k == 0)
{
result = 1;
}
double result1 = 1;
for (int i = 1; i < k + 1; i++)
{ //result*=1/i; //不进行强制转换时,得到的结果是一个整型
result1 *=(double) 1 / i; //借用变量result1 来处理新增加的项
result += (double )(result1 + i * i); //借用变量result 来累加得到的结果
}
return result;
}
}
public class program {
public static void Main(string[] args) {
Calculation mycalculation = new Calculation(10);
double r;
r = mycalculation.GetResult(10);
Console.WriteLine(r);
}
}
从网上借鉴来的代码:
using System;
class Program {
public static int Factorialfunc(int n) { //求n的阶乘
int result=1;
for (int i = n;i>0; i--) {
result *= i;
}
return result;
}
public static void Main(string[] args) {
int k = 10;
double r=0;
double r1 = 0;//r1部分计算平方
double r2 = 0;//r2部分计算阶乘倒数的累加和
for (int i = 0; i < k + 1; i++) {
r1 +=(double) i * i;
r2 += (double)1 / (double)Factorialfunc(i);
}
r = r1 + r2;
Console.WriteLine("The result is " + r);
}
}