Java基础知识复习(二)--流程控制

1.练习-黄金分割点

  • 寻找某两个数相除,其结果 离黄金分割点 0.618最近
  • 分母和分子不能同时为偶数
  • 分母和分子 取值范围在[1-20]
package review2;

public class Test1 {
	public static void main(String[] args) {
	    //黄金分割点
		float breakPoint = 0.618f;
		int fenzi = 1,fenmu = 1;//分子,分母
		float minDiff = 100;
		for(int i = 1; i < 20; i++) {
			for(int j =1;j < 20; j++) {
				if(i%2 == 0 && j%2 == 0) continue;
				float result = (float)i/j;
				//差值
				float diff = result-breakPoint;
				//取绝对值
				diff = diff < 0 ? 0-diff:diff;
							
				if(diff < minDiff) {
					minDiff = diff;
					fenzi = i;
					fenmu = j;					
				}			
			}
		}
		System.out.println("离黄金分割点(" + breakPoint + ")最近的两个数相除是:" +fenzi+"/"+fenmu+"="+(float)fenzi/fenmu);
	}
}

2.练习-水仙花数

水仙花数定义:
1. 一定是3位数
2. 每一位的立方,加起来恰好是这个数本身,比如153=1*1*1+5*5*5+3*3*3

目的:寻找1000以内所有的水仙花数

package review2;

public class Test2 {

	public static void main(String[] args) {
		int flower = 100;		
		for(;flower < 1000; flower++) {
			//中间变量temp
			int temp = flower;
			//个位数
			int i = temp%10;
			temp = temp/10;
			//十位数
			int j = temp%10;
			temp = temp/10;
			//百位数
			int k = temp;
			float result = i*i*i+j*j*j+k*k*k;
			if(result == flower) {
				System.out.println("水仙花数:"+flower);
			}
		 
		}
	}
}

3.练习-小学算术题

package review2;

public class Test3 {
	public static void main(String[] args) {		
		for (int a = 0; a <= 100; a++) {
            for (int b = 0; b <= 100; b++) {
                for (int c = 0; c <= 100; c++) {
                    for (int d = 0; d <= 100; d++) {
						if(a+b == 8 && c-d == 6 && a+c == 14 && b+d == 10) {
							System.out.println("a="+a+"\nb="+b+"\nc="+c+"\nd="+d);
						}
					}	
				}	
			}	
		}	
	}
} 

4.练习-数组最小值

首先创建一个长度是5的数组,然后给数组的每一位赋予随机整数,通过for循环,遍历数组,找出最小的一个值出来0-100的 随机整数的获取办法有多种,下面是参考办法之一: (int) (Math.random() * 100)

Math.random() 会得到一个0-1之间的随机浮点数,然后乘以100,并强转为整型即可。

package review2;

public class Test4 {

	public static void main(String[] args) {
		int[] a = new int[5];
		int min =101;
		for(int i = 0;i < a.length; i++) {
			a[i] = (int) (Math.random()*100);
			System.out.println(a[i]);
		}
		for(int j = 0; j < a.length; j++) {
			if(a[j] < min) {
				min = a[j];
			}
		}
		System.out.println("最小值:"+min);
	}

}

猜你喜欢

转载自blog.csdn.net/qq_41900081/article/details/84720178
今日推荐