要求就是题目,想问一下问题在哪儿啊,还是思路不对 ,。,,;;avbfdbdf
for循环
public static void main(String[] args) {
double s = 0.0;
for (int i = 1; i <= 100; i++) {
s += 1.0 / i * Math.pow(-1, i + 1);
}
System.out.println(s);
}
while循环
public static void main(String[] args) {
double s = 0.0;
int i=1;
while(i<=100) {
s += 1.0 / i * Math.pow(-1, i + 1);
i++;
}
System.out.println(s);
}
如果按照你的思路,应该这样做:
package com;
public class Main {
public static void main(String[] args) {
int i = 1;
double b = 0.0, c = 0.0, d = 0.0, s = 0.0;
while (i <= 100) {
b = 1.0 / i;
// 偶数项
if (i % 2 == 0) {
c += b;
} else { // 奇数项
d += b;
}
i++;
}
s = -c + d;
System.out.println(s);
}
}
就那几个变量初始化一下
最后的输出s的公式没在while循环内,出了循环就是得到的是循环后的最后一个结果
压根没看出来思路是什么....,换个其他简单的思路实现试试呢