我正试图找到一个方程的summ:S=-(2x)^2/2!+(2x)^4/4!-(2x)^6/6!+(2x)^8/8!。。。。
x的间隔是[0.1;1.5]
该代码中还有另一个等式2(cos^2−1),但这会输出正确的答案。这个代码出了什么问题?
Scanner sc = new Scanner(System.in);
System.out.print("x=");
double x = sc.nextDouble();
sc.close();
if (x < 0.1 || x > 1.5) {
System.out.println("error");
return;
}
double s = -((2*x)*x/2) ;
double a = (2*x)*x ;
int i = 2;
while (Math.abs(a) > 0.001) {
a = -a*4*(x*x) ;
s = s + a/(i*(i-1));
i = i + 2;
}
System.out.printf("function=%.4f%n", 2*(Math.cos(x)*Math.cos(x)-1));
System.out.printf("summa=%.4f", s);
}
}
1/
(2*x)*x/2 == 2*x*x/2 == x*x
相同的CCD_ 2不需要括号。
2/
如果"x"大于或等于0.5,则"a"不会降低,因此他不会满足退出循环的条件。
3/我猜想循环的条件是当前的幂除以阶乘小于0.001。
double i = 2; // double for getting the rest too in the division
int neg = -1;
double pow;
double pow_res;
double res = 0;
double loop_check = 1;
while (loop_check > 0.001 || i < 99999) {
pow = i - 1;
pow_res = 2 * x;
while (--pow != 0) // get power result for 2X^n
pow_res = pow_res *(2 * x);
loop_check = pow_res / (i * ((i + 1) / 2)); // save the result for loop check and used after for calculation
res = res + neg * loop_check;
i = i + 2;
neg = -neg;
}