基础篇课后习题答案,做了大部分,虽然不一定是最佳代码,但是保证每个都能运行,如有更好的答案,欢迎讨论
5.1 计算平均值等数学题
Scanner scanner = new Scanner(System.in);
System.out.print("请输入数字,以0结束:");
int num = scanner.nextInt();
int positive = 0, negative = 0;
double total = 0d, average = 0d;
if (num != 0) {
while (num != 0) {
if (num > 0) {
positive++;
} else {
negative++;
}
total = total + num;
num = scanner.nextInt();
}
average = total / (positive + negative);
} else {
System.out.println("起始数字不能为0");
}
System.out.println("正数的个数是:" + positive);
System.out.println("负数的个数是:" + negative);
System.out.println("总和是:" + total);
System.out.println("平均数是:" + average);
5.2 重复加法
Scanner scanner = new Scanner(System.in);
int count = 0;
int correct = 0;
while (count <= 20) {
int num1 = (int) (Math.random() * 10);
int num2 = (int) (Math.random() * 10);
System.out.print(num1 + " + " + num2 + " = ");
int answer = scanner.nextInt();
if (answer == num1 + num2) {
System.out.println("你答对了!");
correct++;
} else {
System.out.println("你答