关于循环和数组 分别给出以下两个例子
循环
一:计算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);
}
}