隨機生成三百道四則混合運算題目程式

one./發表於2024-04-23

2252136 2252130
這位是一個程式,可以隨機生成300道四則混合運算題目程式,並可以輸入題號做題,輸入答案後,程式會判定你做的是否對。

點選檢視程式碼
public class Operation {
    public static void main(String[] args) {
        List<String> validEquations = generateValidEquations(300);
        Scanner scanner = new Scanner(System.in);
        boolean continueAnswering = true;

        while (continueAnswering) {
            for (int i = 0; i < validEquations.size(); i++) {

                System.out.println((i + 1) + ": " + validEquations.get(i).replace('*', '×').replace('/', '÷'));
            }

            System.out.println("請輸入您要解答的題號 (1-300):");
            int questionNumber = scanner.nextInt();

            if (questionNumber < 1 || questionNumber > 300) {
                System.out.println("輸入的題號無效。程式退出。");
                continue;
            }

            String selectedEquation = validEquations.get(questionNumber - 1).replace(" = ?", "");
            System.out.println("請解答以下等式: " + selectedEquation.replace('*', '×').replace('/', '÷'));

            double correctAnswer = evaluateExpression(selectedEquation);
            System.out.println("請輸入您的答案:");
            double userAnswer = scanner.nextDouble();

            if (Math.abs(correctAnswer - userAnswer) < 0.01) {
                System.out.println("回答正確!");
            } else {
                System.out.printf("回答錯誤!正確答案是:%.2f\n", correctAnswer);
            }

            System.out.println("您想繼續做題嗎?(yes/no)");
            String answer = scanner.next();
            continueAnswering = "yes".equalsIgnoreCase(answer);
        }

        scanner.close();
        System.out.println("感謝您的參與!");
    }

    public static List<String> generateValidEquations(int count) {
        List<String> equations = new ArrayList<>();
        Random random = new Random();
        while (equations.size() < count) {
            String equation = generateEquation(random);
            double result = evaluateExpression(equation);
            if (result > 0 && result < 1000 && result == Math.floor(result)) {
                equations.add(equation + " = ?");
            }
        }
        return equations;
    }

    public static String generateEquation(Random random) {
        int num1 = random.nextInt(100) + 1;
        int num2 = random.nextInt(100) + 1;
        int num3 = random.nextInt(100) + 1;
        char operator1 = generateOperator(random);
        char operator2 = generateOperator(random);
        return String.format("%d %c %d %c %d", num1, operator1, num2, operator2, num3);
    }

    public static char generateOperator(Random random) {
        char[] operators = {'+', '-', '*', '/'};
        return operators[random.nextInt(operators.length)];
    }

    public static double evaluateExpression(String expression) {
        // Simple evaluation logic
        String[] postfix = infixToPostfix(expression);
        return evaluatePostfix(postfix);
    }

    private static String[] infixToPostfix(String expression) {
        List<String> postfix = new ArrayList<>();
        Stack<Character> operators = new Stack<>();
        StringTokenizer tokenizer = new StringTokenizer(expression, " +-*/()", true);
        while (tokenizer.hasMoreTokens()) {
            String token = tokenizer.nextToken().trim();
            if (token.isEmpty()) {
                continue;
            }

            char c = token.charAt(0);
            int idx = "+-*/".indexOf(c);

            if (idx != -1) {
                while (!operators.isEmpty() && precedence(operators.peek()) >= precedence(c)) {
                    postfix.add(String.valueOf(operators.pop()));
                }
                operators.push(c);
            } else if (c == '(') {
                operators.push(c);
            } else if (c == ')') {
                while (!operators.isEmpty() && operators.peek() != '(') {
                    postfix.add(String.valueOf(operators.pop()));
                }
                operators.pop();
            } else {
                postfix.add(token);
            }
        }

        while (!operators.isEmpty()) {
            postfix.add(String.valueOf(operators.pop()));
        }

        return postfix.toArray(new String[0]);
    }

    private static int precedence(char op) {
        switch (op) {
            case '+':
            case '-':
                return 1;
            case '*':
            case '/':
                return 2;
            default:
                return -1;
        }
    }

    private static double evaluatePostfix(String[] postfix) {
        Stack<Double> stack = new Stack<>();
        for (String token : postfix) {
            if (token.length() == 1 && "+-*/".contains(token)) {
                double b = stack.pop();
                double a = stack.pop();
                switch (token.charAt(0)) {
                    case '+':
                        stack.push(a + b);
                        break;
                    case '-':
                        stack.push(a - b);
                        break;
                    case '*':
                        stack.push(a * b);
                        break;
                    case '/':
                        stack.push(a / b);
                        break;
                }
            } else {
                stack.push(Double.parseDouble(token));
            }
        }
        return stack.pop();
    }
}

答案正確:

答案錯誤:

相關文章