Java 作业一
1、用递归算法变成求Fibonacci数列的前20个数。
package one;
public class SimplemMenu {
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 1; i <= 20; i++) {
System.out.print(f(i) + " ");
}
System.out.println();
System.out.println("学号+姓名");
}
public static int f(int n) {
if (n == 1 || n == 2) {
return 1;
}
return f(n - 2) + f(n - 1);
}
}
2、编写程序计算三门课的平均成绩,要求应用程序分别用java语言不通的循环语句实现,每门课的成绩用Math类的random()方法随机产生,成绩范围为40~100。(用三种循环结构分别完成)
循环结构for语句
package one;
public class FirstClass2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
int count;
for (int i = 1; i <= 3; i++) {
int num = (int) (60 * Math.random() + 40);
sum = sum + num;
}
count = sum / 3;
System.out.println(count);
System.out.println("学号+姓名");
}
}
循环结构while语句
package one;
public class FirstClass2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0, i = 1;
int count;
while (i <= 3) {
int num = (int) (60 * Math.random() + 40);
sum = sum + num;
i++;
}
count = sum / 3;
System.out.println(count);
System.out.println("学号+姓名");
}
}
循环结构do…while语句
package one;
public class FirstClass2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0, i = 1;
int count;
do {
int num = (int) (60 * Math.random() + 40);
sum = sum + num;
i++;
} while (i <= 3);
count = sum / 3;
System.out.println(count);
System.out.println("学号+姓名");
}
}
3、利用循环语句输出100以内的整数。
package one;
public class Fibonacci {
public static void main(String[] args) {
// TODO Auto-generated method stub
int n = 1;
while (n <= 100) {
System.out.print(n + " ");
if (n % 10 == 0) {
System.out.println("");
}
n++;
}
System.out.print("学号+姓名");
}
}
4、用穷举算法变成求三位数,其各个位、十位和百位数的立方和就是这个数。
package one;
public class FirstClass {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i, y, x, z;
int sum;
for (i = 100; i < 1000; i++) {
x = i / 100;
y = i % 100 / 10;
z = i % 10;
sum = x * x * x + y * y * y + z * z * z;
if (sum == i)
System.out.println(sum);
}
System.out.println("学号+姓名");
}
}