欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java基础算法练习五题——(4)

程序员文章站 2024-03-22 18:51:40
...

16.输出九九乘法表

package com.myd.ex4;

public class MultiNine {

	public static void main(String[] args) {
		for (int i = 1; i <= 9; i++) {
			for (int j = 1; j <= 9; j++) {
				System.out.print(i * j + " ");
			}
			System.out.println("");
		}
	}

}

17.猴子吃桃问题:猴子第一天摘下若干个桃子,当即吃了一半,还不瘾,又多吃了一个 第二天早上又将剩下的桃子吃掉一半,又多吃了一个。以后每天早上都吃了前一天剩下的一半零一个。到第10天早上想再吃时,见只剩下一个桃子了。求第一天共摘了多少。 

package com.myd.ex4;

public class StealPeach {

	public static void main(String[] args) {
		int peach = 1;
		for (int i = 1; i < 10; i++) {
			peach = (peach + 1) * 2;
		}
		System.out.println(peach);

	}

}
18.两个乒乓球队进行比赛,各出三人。甲队为a,b,c三人,乙队为x,y,z三人。以抽签决定比赛名单。有人向队员打听比赛的名单。a说他不和x比,c说他不和x,z比,请编程序找出三队赛手的名单。
package com.myd.ex4;

public class FindPlayer {

	public static void main(String[] args) {
		int i, j, k;
		// 声明i,j,k分别为A,B,C的对手;
		for (i = 'X'; i <= 'Z'; i++) {
			for (j = 'X'; j <= 'Z'; j++) {
				for (k = 'X'; k <= 'Z'; k++) {
					if (i == 'X' || j == i || k == 'X' || k == 'Z' || k == i || k == j)
						continue;
					System.out.print("A,B,C will vs " + (char) i + "," + (char) j + "," + (char) k);
				}
			}
		}

	}

}
19.打印7行的菱形。

package com.myd.ex4;

public class PrintDiamond {

	public static void main(String[] args) {
		
		for (int i = 1; i <= 4; i++) {
			
			for (int j = 1; j <= 4 - i; j++) {System.out.print(" ");}
			
			for (int k = 1; k <= i * 2 - 1; k++) {System.out.print("*");}
			
			System.out.println();
		}
		
		for (int x = 3; x >= 1; x--)
		{
			for (int y = 1; y <= 4 - x; y++){System.out.print(" ");}
			
			for (int z = 4 - x; z <= 2 + x; z++){System.out.print("*");}
			
			System.out.println();
		}

	}

}
20.有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13...求出这个数列的前20项之和。 

package com.myd.ex4;

public class SeqSum {

	public static void main(String[] args) {
		int length = 20;
		double sum = 2;
		double[] A = new double[length]; // 分子
		double[] B = new double[length]; // 分母
		A[0] = 2;
		B[0] = 1;
		for (int i = 1; i < length; i++) {
			B[i] = A[i - 1];
			A[i] = B[i - 1] + B[i];
			sum += A[i] / B[i];
		}
		System.out.println(sum);
		System.out.println(A[length - 1] + " " + B[length - 1]);
	}

}