第五章第二题(重复加法)(Repeat additions)

第五章第二题(重复加法)(Repeat additions)

  • 5.2(重复加法)程序清单5-4产生了5个随机减法问题。改写该程序,使它产生10个随机加法问题,加数是两个1到15之间的整数。显示正确答案的个数和完全测试的时间。
    5.2(Repeat multiplications) Listing 5.4, SubtractionQuizLoop.java, generates five randomsubtraction questions. Revise the program to generate ten random addition questions for two integers between 1 and 15. Display the correct count and test time.
  • 参考代码:
package chapter05;

import java.util.Scanner;

public class Code_02 {
    public static void main(String[] args) {
        int correctCount = 0,count = 0;
        long startTime = System.currentTimeMillis();
        String output = " ";
        Scanner input = new Scanner(System.in);

        while (count < 10) {
            int number1 = (int) (1 + Math.random() * 15);
            int number2 = (int) (1 + Math.random() * 15);

            System.out.print("What is " + number1 + " + " + number2 + "? ");
            int answer = input.nextInt();

            if (number1 + number2 == answer) {
                System.out.println("You are correct!");
                correctCount++;
            }
            else
                System.out.println("Your answer is wrong.\n" + number1 + " + "
                        + number2 + " should be " + (number1 + number2));
            count++;
            output += "\n" + number1 + "+" + number2 + "=" + answer
                    + ((number1 + number2 == answer) ? " correct" : " wrong");
        }

        long endTime = System.currentTimeMillis();
        long testTime = endTime - startTime;

        System.out.println("Correct count is " + correctCount + "\nTest time is "
                + testTime / 1000 + " seconds\n" + output);
    }
}

  • 结果显示:
What is 2 + 12? 14
You are correct!
What is 7 + 13? 20
You are correct!
What is 2 + 11? 13
You are correct!
What is 6 + 4? 10
You are correct!
What is 1 + 9? 10
You are correct!
What is 2 + 11? 13
You are correct!
What is 2 + 15? 17
You are correct!
What is 14 + 14? 18
Your answer is wrong.
14 + 14 should be 28
What is 1 + 8? 9
You are correct!
What is 11 + 7? 18
You are correct!
Correct count is 9
Test time is 37 seconds
 
2+12=14 correct
7+13=20 correct
2+11=13 correct
6+4=10 correct
1+9=10 correct
2+11=13 correct
2+15=17 correct
14+14=18 wrong
1+8=9 correct
11+7=18 correct

Process finished with exit code 0

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值