Java语言程序设计(基础篇)(原书第10版) 练习题答案 第5章

本章节提供了Java语言基础篇第5章的课后习题答案,包括计算平均值、单位转换、找出最高分等题目。代码已实现并确保可运行,欢迎讨论优化方案。
摘要由CSDN通过智能技术生成

基础篇课后习题答案,做了大部分,虽然不一定是最佳代码,但是保证每个都能运行,如有更好的答案,欢迎讨论

 

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("你答
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值