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值
	}
}```

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