java 循环及数组

关于循环和数组 分别给出以下两个例子

循环
一:计算2 + 4 + 6 +…… + 100。

public class Test {
	public static void main(String[] args) {
		int he = 0;
		for (int i = 2; i <= 100; i = i + 2) {
			he = he + i;
		}
		System.out.print("2+4+6+……+100=" + he);
	}
}

二“:计算10!(提示:10!=1×2×3×……×10)


public class Test {
	public static void main(String[] args) {
		int ji = 1;
		for (int i = 1; i <= 10; i++) {
			ji = ji * i;
		}
		System.out.print("10!=" + ji);
	}
}


数组
一:统计给定数组int[] s = { 78, 34, 23, 65, 89, 92, 72, 10, 99 };中偶数的个数,在控制台输出统计结果。

public class Test {
	public static void main(String[] args) {
		int[] s = { 78, 34, 23, 65, 89, 92, 72, 10, 99 };
		int gs = 0;
		for (int i = 0; i < s.length; i++) {
			if (s[i] % 2 == 0) {
				gs ++;
			}
		}
		System.out.println("数组中包含偶数" + gs + "个");
	}
}

二:从给定数组int[] s = { 78, 34, 23, 65, 89, 92, 72, 10, 99 };中找出最大的数输出到控制台。


public class Test {
	public static void main(String[] args) {
		int[] s = { 78, 34, 23, 65, 89, 92, 72, 10, 99 };
		int max = s[0];
		for (int i = 1; i < s.length; i++) {
			if (s[i] > max) {
				max = s[i];
			}
		}
		System.out.println("数组中最大的元素是" + max);
	}
}


三:定义一个数组cj存放8个学生某一门课的成绩:int[] cj = {56, 73, 89, 66, 83, 100, 91, 77};,计算他们的平均分,并把平均分输出到控制台。

public class Test {
	public static void main(String[] args) {
		int[] cj = {56, 73, 89, 66, 83, 100, 91, 77};
		int he = 0;
		//for (int i = 0; i < 8; i++) {
		for (int i = 0; i < cj.length; i++) {
			he = he + cj[i];
		}
		//double pingJun = he / 8;
		double pingJun = he / cj.length;
		System.out.println("8个人的平均成绩为:" + pingJun);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值