1. 程式人生 > >Java程式設計練習1——求三個數大小,一百個數的和

Java程式設計練習1——求三個數大小,一百個數的和

1.求三個數中最小值和最大值

思路1:先定義兩個值min和max賦值給a,然後再將b和c與a進行比較即可

package Hello;

public class test {

	public static void main(String[] args) {
		int a=5,b=7,c=3;
		int min=a;//定義最小值,將a賦給最小值,然後進行比較
		if(b<a){
			min=b;
		}
		if(c<b){
			min=c;
		}
		System.out.println("最小值為:"+min);
		int max=a;//定義最大值,將a賦給最大值,然後進行比較
		if(b>a){
			max=b;
		}
		if(c>b){
			max=b;
		}
		System.out.println("最大值為:"+max);
	}
}

思路2:先定義一箇中間變數temp,再將三個數進行比較。將最大值或最小值賦給temp即可

package Hello;

public class test {

	public static void main(String[] args) {
		int a=5,b=7,c=3;
		int temp;
		if(a<b){
			 temp=a;
			 a=b;
			 b=temp;
		}
		if(a<c){
			temp=a;
			a=c;
			c=temp;
		}
		System.out.println("最大值為:"+a);
		if(a>b){
			 temp=a;
			 a=b;
			 b=temp;
		}
		if(a>c){
			temp=a;
			a=c;
			c=temp;
		}
		System.out.println("最小值為:"+a);
	}
}

思路3:直接運用三目運算子,簡潔明瞭

package Hello;

public class test {

	public static void main(String[] args) {
		int a=5,b=7,c=3;
		int t=(a>b)?a:b;//求a與b之間的最大值
		int max=(t>c)?t:c;//求t與c之間的最大值,也就是三個數中的最大值
		System.out.println("最大值為:"+max);
		int s=(a<b)?a:b;//求a與b之間的最小值
		int min=(s<c)?s:c;//求t與c之間的最小值,也就是三個數中的最小值
		System.out.println("最小值為:"+min);
	}
}

三種演算法的結果均為:

最大值為:7
最小值為:3

2.求一百個數的和

直接運用for迴圈即可

package Hello;

public class test {

	public static void main(String[] args) {
		int sum=0;
		for(int i=1;i<=100;i++){
			sum=sum+i;
		}
		System.out.println(sum);
	}
}

結果:

5050

思考有一行數字序列,第一個數字為1,第二個數字為1+2的和,第三個數字為第二個數字+3的和,第四個數字為第三個數字+4的和...(注意這並不是斐波那契數列);思路其實很簡單,將輸出語句寫到for迴圈裡面即可

package Hello;

public class test {

	public static void main(String[] args) {
		int sum=0;
		for(int i=1;i<=100;i++){
			sum=sum+i;
			System.out.print(sum+" ");
			if(i%5==0){
				System.out.println();
			}
		}
	}
}

結果:

1 3 6 10 15 
21 28 36 45 55 
66 78 91 105 120 
136 153 171 190 210 
231 253 276 300 325 
351 378 406 435 465 
496 528 561 595 630 
666 703 741 780 820 
861 903 946 990 1035 
1081 1128 1176 1225 1275 
1326 1378 1431 1485 1540 
1596 1653 1711 1770 1830 
1891 1953 2016 2080 2145 
2211 2278 2346 2415 2485 
2556 2628 2701 2775 2850 
2926 3003 3081 3160 3240 
3321 3403 3486 3570 3655 
3741 3828 3916 4005 4095 
4186 4278 4371 4465 4560 
4656 4753 4851 4950 5050 

斐波那契數列是這樣的

package Hello;

public class test {

	public static void main(String[] args) {
		int a1=1,a2=1;
		for(int i=1;i<38;i++){
			System.out.printf("%10d %10d",a1,a2);
			a1=a1+a2;//將前面兩個數的和賦值給後面一個數
			a2=a2+a1;//依次迴圈
			if(i%5==0){
				System.out.println();
			}
		}
	}
}

其結果為(注意輸出格式的問題):

         1          1         2          3         5          8        13         21        34         55
        89        144       233        377       610        987      1597       2584      4181       6765
     10946      17711     28657      46368     75025     121393    196418     317811    514229     832040
   1346269    2178309   3524578    5702887   9227465   14930352  24157817   39088169