## 用台劳公式计算cos x的值

sswie 发布于 2011/10/09 23:55

cos x =  1 - x^2/2！ +  x^4/4！ -  x^6/6！+.........

```import java.util.*;
public class Cos {
double x = 0;
double result = 1;

public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
double x = in.nextDouble();
Cos cos = new Cos();
cos.cosX(x);
}

public void cosX(double x)
{
double term = 0;             //每一项，除了第一项
int sign = -1;                  //用于修改符号
double num = x ;            //分子
int deno = 1 ;                 //分母
int i =2,j=1;
do
{
for(;j!=i;j++)
{
num*=num;
deno*= (j+1);
}
term = (sign)*num/deno;
sign*=-1;
i += 2;
result += term;
System.out.println(result);
}while(i<80);

}

}```

0
s

#### 引用来自“xyz555”的答案

```public class Test
{
public static double cosX(double x)
{
double result = 1;
double factorial = 1;                 // 计算阶乘，这里不能使用int会溢出
int tmp = 0;

for(int i = 1; i < 80; ++i)
{
tmp = i << 1;
factorial *= -1 * (tmp - 1) * tmp;
result += Math.pow(x, tmp) / factorial;
}

return result;
}

public static void main(String[] args)
{
double test = 30.0 / 180.0 * 3.14159265;
System.out.println(cosX(test));
System.out.println(Math.cos(test));
}
}```

0

0
w

#### 引用来自“xyz555”的答案

0

0

```public class Test
{
public static double cosX(double x)
{
double result = 1;
double factorial = 1;                 // 计算阶乘，这里不能使用int会溢出

for(int i = 1; i < 80; ++i)
{
factorial *= -1 * (i * 2 - 1) * (i * 2);
result += Math.pow(x, (2 * i)) / factorial;
}

return result;
}

public static void main(String[] args)
{
double test = 30.0 / 180.0 * 3.14159265;
System.out.println(cosX(test));
System.out.println(Math.cos(test));
}
}```

0.8660254040835881

0.8660254040835881

0

```public class Test
{
public static double cosX(double x)
{
double result = 1;
double factorial = 1;                 // 计算阶乘，这里不能使用int会溢出
int tmp = 0;

for(int i = 1; i < 80; ++i)
{
tmp = i << 1;
factorial *= -1 * (tmp - 1) * tmp;
result += Math.pow(x, tmp) / factorial;
}

return result;
}

public static void main(String[] args)
{
double test = 30.0 / 180.0 * 3.14159265;
System.out.println(cosX(test));
System.out.println(Math.cos(test));
}
}```

0