Java數組參數應用&數組偶數識別"以數組偶數比實驗爲例"

  • Q10. Write a method named percentEven that
  • accepts an array of integers as a parameter and returns
  • the percentage of even numbers in the array a
  • s a real number. For example, if a
  • variable named nums refers to an array of the elements
  • {6, 2, 9, 11, 3}, then the call of percentEven(nums)
  • should return 40.0. If the array contains no even elements or
  • no elements at all, return 0.0
import java.util.*;
import java.util.Scanner;
public class Q10 {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner console = new Scanner (System.in);
		System.out.println("Type a integer: ");
		// 輸入數組大小
		int []num = new int[console.nextInt()];
		for (int i=0;i<num.length;i++) {
			System.out.println("#"+(i+1)+" number is: ");
			num[i]=console.nextInt();
		}
		double percentage = percentEven(num);
		//利用數組作爲參數
		System.out.println("The percentage of even number is: "+percentage);
	}
	public static double percentEven (int []array) {
		double result =0.0;
		int count=0;
		int sum=0;
		for (int i=0;i<array.length;i++) {
			if(array[i]%2==0) {
				count++;
			}
			//如果爲偶數 計數加一
			sum++;
			//計算數組大小 也可以用array.length()代替
		}
		if(count==0) {
			result = 0.0;
			//如果count爲0,result爲0.0
		}else{
			result = (double)count/sum*100;
			//輸入百分比
		}
		return result;
		//返回result值
	}
}```

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章