一、需求分析:
- 编写小学四则运算程序,自动生成小学四则运算题目
- 能完成简单的加,减,乘,除运算,,可以通过输入参数来控制随机生成的题目数量
- 能根据用户的输入来选择运算种类如加法运算,减法运算等
- 能让程序接受用户输入答案,并判断对错,最后给出正确率
- 程序一次运行生成的题目不能重复,如2+3与3+2,3*2与2*3等
- 除了整数还应支持真分数四则运算
- 能生成实现混合四则运算,如20-9*4+6-8/3=?
二、设计思路:
- 编写生成随机题目的代码,提示输入题目生成量参数,然后能生成相应数量的题目
- 编写判别确立各运算符在表达式中的优先级,如乘除大于加减等
- 题目要求能支持真分数运算,则为了实现分数和整数的混合运算,可以将整数看成分母为1的真分数,编写真分数的运算程序
- 编写程序,能识别输入的题目答案并进行对比,最后输出正确题目数与正确率
三、部分代码:
- 真分数运算实现代码:
-
public static String caculate(String s){ String ss = s; String end = null; int a1 = ss.charAt(0)-'0'; int a2 = ss.charAt(2)-'0'; int b1 = ss.charAt(4)-'0'; int b2 = ss.charAt(6)-'0'; int c = 1; if(ss.charAt(3)=='-') c = -1; int e1 = a1 * b2 + c * a2 * b1; int e2 = a2 * b2; int e11 = Math.abs(e1); int e22 = Math.abs(e2); if(e1 == 0) end = 0+""; else if(e11 % e22 == 0){ end = e1/e2 +""; }else if(e22 % e11 == 0){ if(e2/e1<0) end = "-" + 1 + "/" +Math.abs(e2/e1); else end = 1 + "/" +e2/e1; }else if(c == 1){ end = e11 + "/" + e22; }else end = "-" + e11 + "/" + e22; return end; }
- 真分数生成代码:
-
public static String caculate(String s){ String ss = s; String end = null; int a1 = ss.charAt(0)-'0'; int a2 = ss.charAt(2)-'0'; int b1 = ss.charAt(4)-'0'; int b2 = ss.charAt(6)-'0'; int c = 1; if(ss.charAt(3)=='-') c = -1; int e1 = a1 * b2 + c * a2 * b1; int e2 = a2 * b2; int e11 = Math.abs(e1); int e22 = Math.abs(e2); if(e1 == 0) end = 0+""; else if(e11 % e22 == 0){ end = e1/e2 +""; }else if(e22 % e11 == 0){ if(e2/e1<0) end = "-" + 1 + "/" +Math.abs(e2/e1); else end = 1 + "/" +e2/e1; }else if(c == 1){ end = e11 + "/" + e22; }else end = "-" + e11 + "/" + e22; return end; } 生成真分数表达式核心代码: public class caculator { //生成真分?表?式 public static String zhen(){ int y = (int) (Math.random()*2)+1;//随机生成运算符的数量 int[] w = new int[10]; String str =null; if(y==1){ char ch = "+-".charAt((int) (Math.random()*2)); for(int i=0;i<(2*y+2);i++){ w[i]= (int) (Math.random()*9)+1; } str = w[0] + "/" + w[1] + ch + w[2] + "/" + w[3] + "="; return str; } if(y==2){ for(int i=0;i<2*y+2;i++){ w[i] = (int) (Math.random()*9)+1; } char ch1 = "+-".charAt((int) (Math.random()*2)); char ch2 = "+-".charAt((int) (Math.random()*2)); str = w[0] + "/" + w[1] + ch1 + w[2] + "/" + w[3] + ch2 + w[4] + "/" + w[5] + "="; return str; } if(y==3){ } return str; } //生成整数表达式 public static String zhengshu(){ int y = (int) (Math.random()*1)+2;//随机生成运算符的数量 int[] in = new int[10]; String str =null; char ch1=0,ch2=0,ch3=0,ch4=0; if(y==2){ for(int i=0;i<y+1;i++){ in[i] = (int) (Math.random()*30)+1; } int num = (int) (Math.random()*2); if(num==0){//左边加括号 ch1 = "+-".charAt((int) (Math.random()*2)); ch2 = "*/".charAt((int) (Math.random()*2)); str = "(" + in[0] + ch1 + in[1] + ")" + ch2 + in[2] +"="; }else{ ch1 = "+-".charAt((int) (Math.random()*2)); ch2 = "*/".charAt((int) (Math.random()*2)); str = in[0] + ch2 + "(" + in[1] + ch1 + in[2] + ")" +"="; } return str; } return str; }
三、结对照片: