Java基础综合练习二 12.27

本文探讨了深秋时节一棵大树上的叶子总数计算问题,通过逆向思维的算法解决。同时,针对一起交通事故中目击者的线索,设计算法找出所有符合条件的车牌号码组合,涉及数字与字母排列组合的计算。

深秋,树叶开始掉落。第一天树叶开始掉落了一半还多一片,第二天又落下了剩下的一半零一片。如此往复循环,直到第十五天,树上还剩一片叶子。问:这颗大树总共有多少片叶子(要求定义一个静态方法)

public static void getAllLeaf(int day) {
		int leaf = 1;
		for(int i = day; i > 1; i--) {
			leaf = (leaf + 1) * 2;
		}
		System.out.println("大树总共有树叶" + leaf + "片");
	}

中国汽车的车牌号除了省份和城市信息,剩下的是数字和字母的五位组合(没有字母i和o)。
有一辆汽车出了事故,司机驾车逃跑,有三位目击者向警方提供线索。
甲:车牌号里面有字母T和R
乙:车牌号里面是三个数字,车牌号开头是T
丙:车牌号里的数字和是15,并且没有相同数字
例如:T24R9就是满足上面的三个条件
当然,满足上面的三个条件的车牌号还有许多,要求写出一个方法找出所有可能的车牌号

public static void getAllCarNumber(){
		List<String> list = new ArrayList<String>();
		for(int x=0; x<=9; x++){
			for(int y=0; y<=9; y++){
				for(int z=0; z<=9; z++){
					if(x==y || y==z || z==x){
						continue;
					}else{
						if(x+y+z==15){
							list.add("" + x + y + z);
						}
					}
				}
			}
		}
		System.out.println(list);
		System.out.println(list.size());
		
		
		List<String> allCarNumber = new ArrayList<String>();
		for(int i=0; i<list.size();i++){
			String str = list.get(i);
			char[] num = str.toCharArray();
			for(int t=0; t<=num.length;t++){
				String carNum= "T";
				for(int a=0;a<t;a++){
					carNum += num[a];
				}
				carNum +='R';
				for(int b=t; b<num.length;b++){
					carNum += num[b];
				}
				allCarNumber.add(carNum);
			}
		}
		System.out.println(allCarNumber);
		System.out.println(allCarNumber.size());
	}

利用公式x1 = (-b + sqrt(bb-4ac))/(2a), x2 = (-b - sqrt(bb-4ac))/(2a)求一元二次方程ax2+ bx + c =0的根,其中a不等于0。
要求写一个方法,参数为三个浮点数a, b, c。分别表示方程ax2 + bx + c =0的系数。
该方法输出一行,表示方程的解。
若b^2 = 4 * a * c,则两个实根相等,则输出形式为:x1=x2=…。
若b^2 > 4 * a * c,则两个实根不等,则输出形式为:x1=…;x2 = …,其中x1>x2。
若b^2 < 4 * a * c,则有两个虚根,则输出:x1=实部+虚部i; x2=实部-虚部i,即x1的虚部系数大于等于x2的虚部系数,实部为0时不可省略。实部 = -b / (2a), 虚部 = sqrt(4ac-bb) / (2*a)

所有实数部分要求精确到小数点后5位,数字、符号之间没有空格。

public void getRootSeeking(double a, double b, double c) {
		if(Math.pow(b, 2) > 4 * a * c) {
			double realPart = -b / (2 *a);
			String str = String.format("%.5f", realPart);
			double xPart = Math.sqrt(Math.abs(4 * a * c - b * b)) / (2 * a);
			String str2 = String.format("%.5f", xPart);
			String x1 = str + "+" + str2 + "i";
			String x2 = str + "-" + str2 + "i";
			System.out.println("x1=" + x1 + ";x2=" + x2);
		} else if(Math.pow(b, 2) < 4 * a * c) {
			double x1 =(-b + Math.sqrt(Math.abs(b * b - 4 * a * c))) / (2 * a); 
			String str = String.format("%.5f", x1);
			double x2 =(-b - Math.sqrt(Math.abs(b * b - 4 * a * c))) / (2 * a); 
			String str2 = String.format("%.5f", x2);
			System.out.println("x1=" + str + ";x2=" + str2);
		} else {
			double x1 =(-b + Math.sqrt(Math.abs(b * b - 4 * a * c))) / (2 * a); 
			String str = String.format("%.5f", x1);
			System.out.println("x1=x2=" + str);
		}
	}
	```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值