一、题目链接
http://noi.openjudge.cn/ch0106/05/
二、解题思路(Java)
◎ 方法public double[] proportion(int[] age)处理所有业务逻辑:
→ 参数age为int类型的数组,存储每个病人患病时的年龄;
→ proportion方法返回double类型的数组,包含四个年龄段患病人数占总患病人数的比例;
◎ 定义四个int类型的整数t1、t2、t3、t4,分别代表四个年龄段的患病人数,初始时均为0;
◎ 定义int类型的整数n,代表患病人数,令n = age.length;
◎ 利用foreach循环遍历获取age的每个元素e:
→ 如果当前元素e小于等于18,则令t1++;
→ 否则如果当前元素e小于等于35,则令t2++;
→ 否则如果当前元素e小于等于60,则令t3++;
→ 否则,令t4++;
foreach循环结束后,t1、t2、t3、t4中分别存储了四个年龄段的患病人数,返回数组如下:
new double[]{100.0 * t1 / n, 100.0 * t2 / n, 100.0 * t3 / n, 100.0 * t4 / n};
◎ 在main方法中调用proportion方法,注入相应的参数后即可获得计算结果,然后按照题目要求的格式输出四个比例。
三、解题思路(C++)
◎ 定义并输入int类型的整数n,代表病人数量;
◎ 定义int类型的数组age[n],用于存储每个病人患病时的年龄;
◎ 定义四个int类型的整数t1、t2、t3、t4,分别代表四个年龄段的患病人数,初始时均为0;
◎ 从第一个病人开始,到最后一个病人为止,利用循环i处理如下:
→ 首先,输入当前病人患病时的年龄age[i];
→ 其次,如果age[i]小于等于18,则令t1++;
→ 否则如果age[i]小于等于35,则令t2++;
→ 否则如果age[i]小于等于60,则令t3++;
→ 否则,令t4++;
循环i结束后,t1、t2、t3、t4中分别存储了四个年龄段的患病人数,因此,100.0 * t1 / n、100.0 * t2 / n、100.0 * t3 / n、
100.0 * t4 / n则代表了四个年龄段患病人数占总患病人数的比例;
◎ 按照题目要求的格式输出四个比例。
四、Java程序
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 e : age) {
if (e <= 18) {
t1++;
}
else if (e <= 35) {
t2++;
}
else if (e <= 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]);
}
}
五、C++程序
#include <iostream>
using namespace std;
int main()
{
int n;
cin >> n;
int age[n];
int t1 = 0;
int t2 = 0;
int t3 = 0;
int t4 = 0;
for (int i = 0; i < n; i++)
{
cin >> age[i];
if (age[i] <= 18)
{
t1++;
}
else if (age[i] <= 35)
{
t2++;
}
else if (age[i] <= 60)
{
t3++;
}
else
{
t4++;
}
}
printf("%.2f%%\n", 100.0 * t1 / n);
printf("%.2f%%\n", 100.0 * t2 / n);
printf("%.2f%%\n", 100.0 * t3 / n);
printf("%.2f%%", 100.0 * t4 / n);
}