面试的一个题目

本文介绍了一个使用Java实现的简单数学表达式生成器。该程序可以随机生成包含加减运算的数学等式,并确保等式的解落在指定范围内。通过不同的case选择,可以生成不同形式的数学题目,适用于教育软件或数学练习应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class test3 {
    public static void main(String[] args){
        int one,two,three,four;
        String strTwo,strThree;
        int i = (int)(Math.random()*4);
        switch(i){
            case 1:
                do{
                    two = getMiddleNum();
                    strTwo = numAddSimbol(two);
                    three = getMiddleNum();
                    strThree = numAddSimbol(three);
                    four = (int)(Math.random()*20);
                }while((four-three-two)<0||(four-three-two)>=20);
                System.out.println("()"+strTwo+strThree+"="+four);
                break;
            case 2:
                do{
                    one = (int)(Math.random()*20);
                    three = getMiddleNum();
                    strThree = numAddSimbol(three);
                    four = (int)(Math.random()*20);
                }while((four-three-one)<=-20||(four-three-one)>=20);
                if((four-three-one)<0) {
                    System.out.println(one + "-()" + strThree + "=" + four);
                }else{
                    System.out.println(one + "+()" + strThree + "=" + four);
                }
                break;
            case 3:
                do{
                    one = (int)(Math.random()*20);
                    two = getMiddleNum();
                    strTwo = numAddSimbol(two);
                    four = (int)(Math.random()*20);
                }while((four-two-one)<=-20||(four-two-one)>=20);
                if((four-two-one)<0){
                    System.out.println(one+strTwo+"-()="+four);
                }else {
                    System.out.println(one + strTwo + "+()=" + four);
                }
                break;
            default:
                do{
                    one = (int)(Math.random()*20);
                    two = getMiddleNum();
                    strTwo = numAddSimbol(two);
                    three = getMiddleNum();
                    strThree = numAddSimbol(three);
                }while((one+two+three)<0||(one+two+three)>=20);
                System.out.println(one+strTwo+strThree+"=()");
                break;
        }

    }
    public static int getMiddleNum(){
        int m,n;
        m = (int)(Math.random()*20);
        n = (int)(Math.random()*-20);
        return m + n;
    }
    public static String numAddSimbol(int x){
        String a;
        if(x>=0){
            a = "+" + x;
        }else{
            a = "" + x;
        }
        return a;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值