Java语言程序设计基础篇第10版第5章习题答案

5.1
1
public class Demo { 2 public static void main(String[] args) { 3 // 创建一个输入对象 4 java.util.Scanner input = new java.util.Scanner(System.in); 5 System.out.print("Enter an integer,the input ends if it is 0: "); 6 //输入一串整数以空格隔开,如果输入0,程序结束 7 int num = input.nextInt(); 8 //定义正数与负数的个数变量,定义输入值得总和(不包括0) 9 int positiveNum = 0, negativeNum = 0; 10 double sum = 0; 11 //判断输入的第一个整数是否为0,如果不是,继续判断,如果是,直接else 12 if (num != 0) { 13 //读入的整数计算正数个数、负数个数、总和,直到读入为0跳出循环 14 while (num != 0) { 15 if (num > 0) 16 positiveNum++; 17 else 18 negativeNum++; 19 sum += num; 20 num = input.nextInt(); 21 } 22 //输出相应的正数、负数、总和和平均数的值 23 System.out.println("The number of positives is " + positiveNum); 24 System.out.println("The number of negatives is " + negativeNum); 25 System.out.println("The total is " + sum); 26 System.out.println("The average is " + sum 27 / (positiveNum + negativeNum)); 28 }else 29 System.out.println("No numbers are entered except 0"); 30 } 31 }

 

5.2
1
public class Demo { 2 public static void main(String[] args) { 3 // 定义问题的数量为10 4 final int NUMBER_OF_QUESTIONS = 10; 5 // 定义变量存放正确的个数,定义变量存放循环次数 6 int correctCount = 0; 7 int count = 1; 8 // 定义开始时间 9 long startTime = System.currentTimeMillis(); 10 // 创建一个输入对象 11 java.util.Scanner input = new java.util.Scanner(System.in); 12 // 随机产生两个整数,循环10次 13 while (count <= 10) { 14 // 定义两个整数变量,存放随机产生的1~15内的整数 15 int num1 = (int) (Math.random() * 15) + 1; 16 int num2 = (int) (Math.random() * 15) + 1; 17 // 输入答案 18 System.out.print("What is " + num1 + " + " + num2 + "? "); 19 int answer = input.nextInt(); 20 // 如果回答正确,正确的个数加一,回答不正确,输出正确的结果 21 if (num1 + num2 == answer) { 22 System.out.println("You are correct!"); 23 correctCount++; 24 } else 25 System.out.println("Your answer is wrong.\n" + num1 + " + " 26 + num2 + " should be " + (num1 + num2)); 27 // 循环次数加一 28 count++; 29 } 30 // 定义结束时间 31 long endTime = System.currentTimeMillis(); 32 // 计算测验时间 33 long testTime = endTime - startTime; 34 // 输出正确答案的个数与测验时间(单位秒) 35 System.out.println("Correct count is " + correctCount 36 + "\nTest time is " + testTime / 1000 + " seconds"); 37 } 38 }

 

转载于:https://www.cnblogs.com/lirun/p/5988959.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值