Discuss / Java / for practices

for practices

Topic source

YANGZY1202

#1 Created at ... [Delete] [Delete and Lock User]
//练习1 给定一个数组,请用for循环倒序输出每一个元素:

public class For_1 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] ns = { 1, 4, 9, 16, 25 };
		for (int i = 0; i < ns.length; i++) {
			System.out.println(ns[i]);
		}

	}
}
//练习2 利用for each循环对数组每个元素求和:

public class For_2 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		int[] ns = { 1, 4, 9, 16, 25 };
		int sum = 0;
		for (int n : ns) {
			sum += n;
		}
		System.out.println(sum); // 55
	}

}

//练习3 利用for循环计算π:

public class For_3 {

	public static void main(String[] args) {
		double pi_quarter = 0.0;
		double flag = 1.0;
		for (int i = 1; i < 10000; i += 2, flag = -flag) {
			pi_quarter += flag / i;
		}
		System.out.println(pi_quarter * 4);
	}

}


  • 1

Reply