Discuss / Java / 算是进行个复习

算是进行个复习

Topic source

wssysh

#1 Created at ... [Delete] [Delete and Lock User]
// 求圆周率pi

public class PI {
	public static void main(String[] args) {
		double pi = 0;
		char sign;// 符号标志
		int num = 1000;// 迭代次数提高迭代精度

		// 构建数组
		int[] ns = new int[num];
		for (int i = 0; i < ns.length; i++) {
			ns[i] = i;
		}
		// for each
		for (int n : ns) {
			sign = n % 2 == 0 ? 't' : 'f';
			// switch
			switch (sign) {
			case 't' -> pi += (1.0 / (2 * n + 1));// 正号
			case 'f' -> pi -= (1.0 / (2 * n + 1));// 负号
			default -> System.out.println("Error!");
			}
		}
		pi = pi * 4;
		System.out.println(pi);
	}
}

  • 1

Reply