Discuss / Java / 交作业啦

交作业啦

Topic source

杨森-ys

#1 Created at ... [Delete] [Delete and Lock User]

//第一题

/*分析,若是要倒序输出,则需要计数器 i 从ns的最后一个开始计数,ns有5个元素,则最后一个元素是ns[4]

用ns.lenght得到ns的最大长度为5, 那么 i 的初始值应该为 ns.lenght - 1,每次循环后计数器 -1,即可完成遍历*/

public class ForDemo {

    public static void main(String[] args) {

        int[] ns = { 1, 4, 9, 16, 25 };

        for (int i = ns.length - 1;i >= 0 ;i-- ) {

            System.out.println(ns[i]);

        }

    }

}

//第二题  分析:直接 for each遍历然后求和即可

public class ForDemo {

    public static void main(String[] args) {

        int[] ns = { 1, 4, 9, 16, 25 };

        int sum = 0;

        for (int n:ns) {

            sum = sum + n;

        }

        System.out.println(sum); // 55

    }

//第三题,求π:

 /*

分析:pi的公式知道,pi/4等于1,3,5,7,9....为分母的求和,前面的符号为,正负正负交替(用 -1 幂次方来完成),

构建计数器 int n = 1(初始值为1,此处需要用int,否则 i / 2会是小数),每次+2就可以得到奇数列

Math.pow(-1,(n/2))/n就是每一项的值

求和即可得到pi/4,

*/

public class ForDemo {

    public static void main(String[] args) {

        double pi = 0;

        for (int n = 1; n < 1000000000; n = n + 2 ) {

            pi = pi + Math.pow(-1, (n/2))/n;

        }

        System.out.println(pi*4);

    }

}


  • 1

Reply