标签:ace 整数 nbsp addition except gen sub src 代码
与运算相关的代码 // 自定义除法运算,两种形式 public static String division(String str1, String str2) { if(str2.equals("0")) { try { throw(new Exception("除数不能为0")); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } int[] a = decompose(str1); int[] b = decompose(str2); int c = (a[0] * a[2] + a[1]) * b[2]; int d = a[2] * (b[0] * b[2] + b[1]); return division(c, d); } public static String division(int str1, int str2) { if (str1 % str2 == 0) { return String.valueOf(str1 / str2); } int[] str = reduction(str1, str2); if (str1 > str2) { int s = str[0] / str[1]; int t = str[0] - str[1] * s; return s + "‘" + t + "/" + str[1]; } else { return str[0] + "/" + str[1]; } } // 自定义乘法运算 public static String mutip(String str1, String str2) { int[] a = decompose(str1); int[] b = decompose(str2); int c = (a[0] * a[2] + a[1]) * (b[0] * b[2] + b[1]); int d = a[2] * b[2]; return division(c, d); } // 自定义加法运算 public static String addition(String str1, String str2) { int[] a = decompose(str1); int[] b = decompose(str2); int c = ((a[0] * a[2] + a[1]) * b[2]) + ((b[0] * b[2] + b[1]) * a[2]); int d = a[2] * b[2]; return division(c, d); } // 自定义减法运算 public static String subtraction(String str1, String str2) { int[] a = decompose(str1); int[] b = decompose(str2); int c = ((a[0] * a[2] + a[1]) * b[2]) - ((b[0] * b[2] + b[1]) * a[2]); int d = a[2] * b[2]; return division(c, d); } // 约分 private static int[] reduction(int a, int b) { for (int i = 2; i < RANG / 2; i++) { while (a % i == 0 && b % i == 0) { a = a / i; b = b / i; } } int[] as = { a, b }; return as; } private static int[] decompose(String str) { int[] container = new int[3]; if (str.contains("‘")) { container[0] = Integer.parseInt(str.split("‘")[0]); container[1] = Integer.parseInt(str.split("‘")[1].split("/")[0]); container[2] = Integer.parseInt(str.split("‘")[1].split("/")[1]); } else if (str.contains("/")) { container[0] = 0; container[1] = Integer.parseInt(str.split("/")[0]); container[2] = Integer.parseInt(str.split("/")[1]); } else { container[0] = 0; container[1] = Integer.parseInt(str); container[2] = 1; } return container; }
测试-1(整数运算)
测试-2(分数运算)
测试-3(真分数运算)
测试-4(较大数运算)
测试-5(除数为0)
测试-6(整数和分数运算)
标签:ace 整数 nbsp addition except gen sub src 代码
原文地址:http://www.cnblogs.com/jscq/p/7751316.html