[Java] 实验7参考代码,代码已更新,感兴趣的同学可以去学习!
1. default package问题可参考实验6
2. for, if, while等,后面包含多条语句时,需要用花括号括起来
3. 为什么需要close scanner, 可参考实验6 (已简要更新原因)
40035 输出某月的天数
1. 较简便的switch-case的写法
switch(month) {
case 1:
case 3:
// Output 31 when month equals 1 or 3
System.out.println(31);
break;
case 2:
// todo. Note that you can use "if" statement in "case"
case 4:
case 6:
// ...
}
We have the coding principle: DRY (Do not repeat yourself.)
2. 闰年的定义
满足如下条件中,任意一条,即为闰年。考虑年份n,
- 若n能被4整除,但不能被100整除
- 若n能被400整除
3. 本地运行正确,提交“答案错误”的同学,可以考察如下case:
year = 1900, month = 2
year = 2000, month = 2
...
大家要自己设计一些case, 去验证“特殊情况”、“边际条件”等。
40037 计算不及格的人数
1. 程序如何停止,请类比40008. 求奇数和那题。
更新:该题代码已在实验6 参考代码中给出。
2. 在第二行输出结果错误(平均分输出73.75, 或者不及格人数输出3)的同学,可以参考实验六“求1+1/2+1/3+……+1/n”那题,第3点。
通俗版代码:(我还没有原题对应的程序,待补充)
进阶代码:
import java.util.Scanner;
public class GradeStatistics {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int repeat = in.nextInt();
while (repeat-- != 0) {
double gradeTot = 0; // gradeTotal, the sum of the input grades
int gradeCnt = 0; // gradeCount, the number of the input grades
int failCnt = 0; // failCount, the number of the grades, which is < 60
for (int grade = in.nextInt(); grade >= 0; grade = in.nextInt()) {
gradeTot += grade;
++ gradeCnt;
failCnt += grade < 60? 1: 0;
}
double average = gradeTot / gradeCnt;
System.out.println("average=" + Math.round(average * 100) / 100d);
System.out.println("count=" + failCnt);
}
}
}
50001
要编写函数fact, 注意到,函数主要由:返回值、函数名、参数列表、函数体组成。
不理解的同学可以自行查阅参考书。
50002
这题要求定义的函数fn, 它的参数列表是要填写两个参数的。