数列求和
作者:互联网
1+1/2+1/3+…+1/n 从右往左更加精确
import java.util.Scanner;
class Main {
public static void main(String[] args){
int n = 50_000;
double sum = 0;
for(int i = 1; i <= n; i++){//从左往右加
sum += 1.0 / i;
}
System.out.print("The result is: " + sum);
double sum1 = 0;
for(int i = n; i > 0; i--){//从右往左加 更加精确
sum1 += 1.0 / i;
}
System.out.print("\nThe result is: " + sum1);
}
}
1/3 + 3/5 + 5/7+…+ 95/97 + 97/99
import java.util.Scanner;
class Main {
public static void main(String[] args){
double sum = 0;
for(int i = 1; i <= 97;i = i+2)
sum += (double)i / (i + 2);
System.out.print("The sum is: " + sum);
}
}
PI = 4 * (1-1/3+1/5-1/7+…+1/(2i-1)-1/(2i+1))
显示当i为10,000 20,000 … 100,000时PI的值
import java.util.Scanner;
class Main {
public static void main(String[] args){
double PI = 0;
double result = 0;
int n = 10_000;
System.out.print("i\t\tPI");
while(n <= 100_000){
for(int i = 1; i <= n; i = i + 2)
result += 1.0 / (2 * i -1) - 1.0 / (2 * i + 1);
PI = 4 * result;
System.out.print("\n" + n + "\t" + PI);
result = 0;
n += 10_000;
}
}
}
标签:java,数列,求和,double,int,000,static,Main 来源: https://www.cnblogs.com/doudou-20123/p/16313009.html