编程与数学(质数, 不足0.5元 按照0.5元收取)

质数

  • 定义:质数又称素数。一个大于1的自然数,除了1和它自身外,不能被其他自然数整除的数叫做质数;否则称为合数(规定1既不是质数也不是合数)。
  • 注意2是最小的质数(也叫素数),也是唯一的偶质数。

代码实现

public class Prime {
    public static void main(String[] args) {
        //判断7是不是质数
        int a = 7;
        int c = 0;
        for (int b = 2; b < a; b++) {
            if (a % b != 0) {
                c++;
            }
        }
        //质数大于等于2 不能被它本身和1以外的数整除
        if (c == a - 2) {
            System.out.println(a + "是质数");
        } else {
            System.out.println(a + "不是质数");
        }
        boolean b = testIsPrime2(2);
        System.out.println(b);
    }

    /**
     * 2是最小的质数(也叫素数),也是唯一的偶质数,
     * @param n
     * @return
     */
    public static boolean testIsPrime2(int n) {
        if (n <= 3) {
            return n > 1;
        }

        for (int i = 2; i < n; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * 优化后
     * @param n
     * @return
     */
    public static boolean testIsPrime3(int n) {
        if (n <= 3) {
            return n > 1;
        }
        //在一般领域,对正整数n,如果用2到 之间的所有整数去除,均无法整除,则n为质数。
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
}

需求说明

⑴当次客运班车开车时间2小时前办理退票,按票面金额的10%计收,不足0.5元按0.5元计算;
⑵当次客运班车开车前2小时以内办理退票,按票面金额的20%计收,不足1元按1元计收;

实现方式

  1. 不足0.5元 按照0.5元收取,这个可以先通过Math.floor()方法向下取整
System.out.println("3.88的值:"+Math.floor(3.88));//3.0
System.out.println("3.48的值:"+Math.floor(3.48));//3.0
System.out.println("3的值:"+Math.floor(3));//3.0
System.out.println("-3.88的值:"+Math.floor(-3.88));//4.0
System.out.println("-3.48的值:"+Math.floor(-3.48));//4.0
  1. 得到整数后判断是否满足条件
       	double currentScore =3.88;
        double floor = Math.floor(currentScore);//3
        if (floor + 0.5 < currentScore) {
            currentScore = floor + 1;
        } else if (floor + 0.5 == currentScore + 0.5) {
            currentScore = floor;
        } else {
            currentScore = floor + 0.5;
        }
        System.out.println(currentScore);//4
    }
  • 不足1元按1元计收;
BigDecimal multiply = new BigDecimal("3.45");
MathContext mathContext = new MathContext(1,RoundingMode.CEILING);
System.out.println(multiply.round(mathContext));//4
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值