算法上机作业,本来用C语言写,但VScode一直抽风,最近学校在上Java,不妨换种语法写
目前感受:JavaSE的语法其实和C没啥区别,换汤不换药
1、问题
典型的斐波那契数列
1 、 1 、2 、 3 、 5 、8 、 13 、 21 、34…
2、解决
① 方法一
迭代关系式 y[ i ] = y[ i-1 ] + y[ i-2 ]
public class Rabit_1 {public static void main(String[] args) {int[] arr=new int[3];int i,j;System.out.println("请输入当前的月数");Scanner scanner=new Scanner(System.in);jInt();arr[0]=arr[1]=1; //1,2月兔子个数为1System.out.println("arr[1] = "+arr[0]);System.out.println("arr[2] = "+arr[1]);for(i=2;i<j;i++){arr[2]=arr[1]+arr[0];System.out.println("arr["+(i+1)+"] = "+arr[2]);arr[0]=arr[1];arr[1]=arr[2];}}
}
② 方法二
迭代关系式
a = b+c; b = a+c; c = a+b;
public class Rabit2 {public static void main(String[] args) {int a=1,b=1,c,i;for(i=1;i<=4;i++){c=a+b;a=b+c;b=c+a; //输出的结果不完美System.out.print(a+" "+b+" "+c+" ");}}
}
③ 方法三
迭代关系式
a = a+b; b = a+b;
public class Rabit3 {public static void main(String[] args) {int i,a=1,b=1;System.out.print(a+" "+b+" ");for(i=1;i<=5;i++){a=a+b;b=a+b;System.out.print(a+" "+b+" ");}}
}
1、方法一
穷举法
public class Gongyueshu_1 {public static void main(String[] args){int a,b,t;System.out.println("输入两个整数");Scanner scanner=new Scanner(System.in);aInt();bInt();t=a<b? a: b; //取ab中较小的数while(!(a%t==0&&b%t==0)){t--;}System.out.println(a+"和"+b+"的最大公约数为 "+t);}
}
2、方法二
辗转相除法
public class Gongyueshu_2 {public static void main(String[] args) {int a,b,r,a1,b1;System.out.println("请输入两个整数");Scanner scanner=new Scanner(System.in);aInt();bInt();a1=a;b1=b;while(b!=0){r=a%b;a=b;b=r;}System.out.println(a1+"和"+b1+"的最大公约数是 "+a);}
}
3、方法三
相减法
public class Gongyueshu3 {public static void main(String[] args) {Scanner scanner=new Scanner(System.in);int a,b;System.out.println("请输入两个整数");aInt();bInt();if(a==b) {System.out.println("最大公约数是:" + a);}else{while(a!=b){if(a>b)a=a-b;elseb=b-a;}System.out.println("最大公约数是:" + a);}}
}
1、介绍
之前上课老师讲到this这个关键字的时候,this.变量名倒是讲清楚了
① 直接引用
this 指向当前对象本身
② 避免重复
形参与成员变量重复,用this区分
③ this( )
引用构造函数
this(参数):调用本类中另一种形式的构造函数(应该为构造函数中的第一条语句)。
2、代码
① Person类
② 主函数Main
本文发布于:2024-02-01 04:08:15,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170673169733745.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |