一、题目链接
http://noi.openjudge.cn/ch0106/05/
二、解题思路
⑴ 通过循环和if...else if...else结构,将n个病人按照四个年龄段分类统计各自人数,再计算各自比例即可;
⑵ 显然,方法proportion需要注入一个参数:int[] age,存储每个病人患病时的年龄,方法proportion的返
回值为double,存储四个年龄段患病人数占总患病人数的比例。
三、程序代码
import java.util.Scanner;
public class Main {
public double[] proportion(int[] age) {
int t1 = 0;
int t2 = 0;
int t3 = 0;
int t4 = 0;
int n = age.length;
for (int i = 0; i < n; i++) {
if (age[i] <= 18) {
t1++;
}
else if (age[i] <= 35) {
t2++;
}
else if (age[i] <= 60) {
t3++;
}
else {
t4++;
}
}
return new double[]{100.0 * t1 / n, 100.0 * t2 / n,
100.0 * t3 / n, 100.0 * t4 / n};
}
public static void main(String[] args) {
Main test = new Main();
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] ages = new int[n];
for (int i = 0; i < n; i++) {
ages[i] = input.nextInt();
}
double[] ans = test.proportion(ages);
System.out.printf("%.2f%%\n", ans[0]);
System.out.printf("%.2f%%\n", ans[1]);
System.out.printf("%.2f%%\n", ans[2]);
System.out.printf("%.2f%%", ans[3]);
}
}