public class BargainUtils { private static final int DEF_DIV_SCALE = 10; /** * 提供(相对)精确的除法运算。当发生除不尽的情况时,由scale参数指 定精度,以后的数字四舍五入。 * * @param v1 * 被除数 * @param v2 * 除数 * @param scale * 表示表示需要精确到小数点以后几位。 * @return 两个参数的商 */ public static double div(double v1, double v2, int scale) { if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b1 = new BigDecimal(Double.toString(v1)); BigDecimal b2 = new BigDecimal(Double.toString(v2)); return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } /** * 提供(相对)精确的除法运算,当发生除不尽的情况时,精确到 小数点以后10位,以后的数字四舍五入。 * * @param v1 * 被除数 * @param v2 * 除数 * @return 两个参数的商 */ public static double div(double v1, double v2) { return div(v1, v2, DEF_DIV_SCALE); } /** * 提供精确的小数位四舍五入处理。 * * @param v * 需要四舍五入的数字 * @param scale * 小数点后保留几位 * @return 四舍五入后的结果 */ public static double round(double v, int scale) { if (scale < 0) { throw new IllegalArgumentException( "The scale must be a positive integer or zero"); } BigDecimal b = new BigDecimal(Double.toString(v)); BigDecimal one = new BigDecimal("1"); return b.divide(one, scale, BigDecimal.ROUND_HALF_UP).doubleValue(); } /** * 生成每次砍价能砍多少 * @param p 砍价次数 * @param m 总砍价金额 * @return */ public static Object[] buildPriceArr(int p ,double m) { double minMoney = div (Math.random () * 9, 100); double d = div (2 * (m - p * minMoney), p * (p - 1), 3); double total = 0; double tem; Object[] arr = new Object[p]; for (int i = 0; i < p; i++) { if (m - total <= 0) { break; } tem = round (minMoney + (p - i - 1) * d, 2); arr[i] = tem; } handel (arr, 0); double totalPre = 0.0; for (int i = 0; i < arr.length; i++) { if(i!=arr.length-1){ totalPre+=(double)arr[i]; } } arr[arr.length-1] = round(m-totalPre,2); return arr; } private static void handel(Object[] arr, int low) { int start = low; double b = div (Math.random () * 9, 100); double tem; for (int i = start; i < arr.length; i++) { tem = (Double)arr[i]; if (tem > 0.1) { arr[low] = round ((Double) arr[low] + tem * b, 2); arr[i] = round (tem - tem * b, 2); } } low += 3; if (arr.length > low && (Double)arr[low] >= 0.1) { handel (arr, low); } } public static void main(String[] args) { String arrStr = Arrays.toString(BargainUtils.buildPriceArr(10,450)); System.out.println(arrStr); } }