题目:
1. 编程实现键盘输入一个人的出生年份,计算出他一生能过几个同年(以100岁为寿命
长度)。
2. 用while 循环求Fibonacci 序列。
1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 …
{
Fo=0
F1=1
Fn=Fn-1+Fn-2,n≥2
}
第一题:(判断在有生之年能过多少闰年)
自己敲的代码:
闰年=能被4整除并且不能被100整除 || 能被400整除
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner jjj = new Scanner(System.in);
int sui = jjj.nextInt();
int count = 0;
for (int i = sui; i <= sui + 100; i++) {
if ((i % 400) == 0) {
count++;
} else if ((i % 4 == 0) && (i % 100) != 0) {
count++;
}
}
System.out.print(count);
}
}
AL官方代码:
官方代码可读性更高
定义两个变量来活的岁数,运用布尔函数来解决求闰年的问题,真妙。
import java.util.Scanner;
public class Nain {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入出生年份: ");
int birthYear = scanner.nextInt();
int endYear = birthYear + 100;
int leapYearCount = 0;
for (int year = birthYear; year <= endYear; year++) {
if (isLeapYear(year)) {
leapYearCount++;
}
}
System.out.println("从" + birthYear + "年到" + endYear + "年,共有" + leapYearCount + "个闰年。");
}
private static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}
第二题:(实现斐波那契数列,并打印前n项)
重点:三个变量转换相连的三项数列
自己敲的代码(仿照):
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner jjj = new Scanner(System.in);
int a = 1;
int b = 1;
int n = jjj.nextInt();
int i=1;
while(i<=n){
System.out.print(a+" ");
int temp = a;
a=b;
b=temp+a;
i++;
}
}
}
AL敲的代码:
public class Nain {
public static void main(String[] args) {
int n = 10; // 要打印的斐波那契数的个数
int current = 0, next = 1, temp;
int count = 0;
while (count < n) {
System.out.print(current + " ");
temp = current;
current = next;
next = temp + next;
count++;
}
}
}