敲java代码--第二章复现作业(上)

文章讲述了如何用Java编程实现计算一个人一生能过的闰年数量,以及生成前n项Fibonacci数列的过程,包括自写代码和官方可读性更高的版本。
摘要由CSDN通过智能技术生成

题目:

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++;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值