求给定序列前 N项和(1-1/2+1/3-00:输入一个正整数n,计算序列1-1/2+1/3-.33的前n项之和
时间: 2023-11-24 15:05:55 浏览: 91
There always exists at least one prime between x and x+x^{1/2}log x
以下是两种Java实现给定序列前N项和的例子:
1.使用for循环实现
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
double sum = 0;
for (int i = 1; i <= n; i++) {
if (i % 2 == 1) {
sum += 1.0 / i;
} else {
sum -= 1.0 / i;
}
}
System.out.printf("前%d项和为:%.2f", n, sum);
input.close();
}
}
```
2.使用while循环实现
```java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int n = input.nextInt();
double sum = 0;
int i = 1;
while (i <= n) {
if (i % 2 == 1) {
sum += 1.0 / i;
} else {
sum -= 1.0 / i;
}
i++;
}
System.out.printf("前%d项和为:%.2f", n, sum);
input.close();
}
}
```
阅读全文