Java基礎知識複習(二)--流程控制
阿新 • • 發佈:2018-12-30
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);
}
}