public class Sum{
public static void main(String[] args){
int flag = -1;
double step = 3.0;
double sum = 1.0;
while(step < 102){
sum += flag/step;
step += 2;
flag *= -1;
}
System.out.println(sum);
}
}
我还是个JAVA菜鸟,尝试着编了一下。哎~耗费不少时间啊,希望对你有帮助。
public class Sum
{
public static void main(String args[])
{
float s = 0;
int i = 1;
while(i <= 101)
{
if ((i + 1) % 4 == 0)
{
s = s - 1/(float)i ;
}
else
{
s = s + 1/(float)i;
}
i=i+2;
}
System.out.println(s);
}
}
不知道能不能行。java中 1除以任何数都得0
public void opNumber(int n) {
String str = "";
String op = "-";
double number = 0;
for (int i = 1; i < n; i += 2) {
if (str.equalsIgnoreCase("") && i == 1) {
str = i + op;
number = i;
} else {
if (op.equals("-")) {
number = number - 1 / i;
op = "+";
} else {
number = number + 1 / i;
op = "-";
}
if (i == n - 1 || i == n - 2) {
str += "1/" + i + "=" + number;
} else {
str += "1/" + i + op;
}
}
}
System.out.println(str);
}
float value = 0;
float num = 1;
for(float i=1;i<=101;i= i+2){
if(num%2 != 0){
value = value + 1/i;
}else{
value = value - 1/i;
}
num++;
}
System.out.println(value);
楼上应该用float
public class Test{
public static void main(String [] args){
float x=0f;
for(int i=1;i<=101;i=i+4){
x=(1.0f/(float)i)+x;
}
for(int i=3;i<=101;i=i+4){
x=x-1.0f/(float)(i);
}
System.out.println(x);
}
}