Discuss / Java / 练习

练习

Topic source
//练习1
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        
        for (int i=4; i >= 0 ; i--) {
            System.out.println(ns[i]);
        }
    }
}
//练习2
public class Main {
    public static void main(String[] args) {
        int[] ns = { 1, 4, 9, 16, 25 };
        int sum = 0;
        for (int n : ns) {
        	sum += n;
        }
        System.out.println(sum);
    }
}
//练习3
public class Main {
    public static void main(String[] args) {
        double pi = 0.0;
        int sign = 1;
        //100000为迭代次数,最终的pi为近似值
        for (int i = 0; i < 100000; i++) {
        	double term = 1.0/(2 * i + 1);
        	pi += sign * term;
        	sign *= -1;
        }
        pi *= 4;
        System.out.println(pi);
    }
}

  • 1

Reply