简单的四则运算题目生成器
设计思想:通过for循环调用方法生成题目并输出结果,将加减乘除运算符用数组储存起来,在0~3之间生成一个随机数来决定运算符,另外在0~100之间生成两个随机数,进行四则运算,如果进行的是除法运算,先判断第二个随机数是否为零,如果为零则将第二个数重新赋值为1,再另用方法计算并输出结果。
原程序代码:
package 四则运算;
import java.util.Random;
import java.util.*;
public class Sizeyunsuan {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("请输入您需要的题目数量:");
int i = scan.nextInt();
for (int m = 0; i > m;) {
timu();
i--;
}
}
//生成题目
public static void timu() {
String fuhao[] = { "+", "-", "*", "/" };
int suiji1 = new Random().nextInt(101);
int suiji2 = new Random().nextInt(101);
int fh = new Random().nextInt(4);
int daan = 0;
if (fh == 0) {
daan = suiji1 + suiji2;
System.out.println(suiji1 + fuhao[fh] + suiji2 + "=" + " (答案:" + daan + ")");
}
else if (fh == 1) {
daan = suiji1 - suiji2;
System.out.println(suiji1 + fuhao[fh] + suiji2 + "=" + " (答案:" + daan + ")");
}
else if (fh == 2) {
daan = suiji1 * suiji2;
System.out.println(suiji1 + fuhao[fh] + suiji2 + "=" + " (答案:" + daan + ")");
}
else if (fh == 3) {
if (suiji2 == 0) {
suiji2++;
}
System.out.print(suiji1 + fuhao[fh] + suiji2 + "=");
chufa(suiji1, suiji2);
}
}
//除法的答案显示,包含显示分数
public static void chufa(int a, int b) {
int m = 0;
if (a==0||b == 1) {
System.out.println(" (答案:" + a / b + ")");
}
else if (a == 1 && b != 1) {
System.out.println(" (答案:" + a + "/" + b + ")");
}
else if (a != 1 || b != 1) {
if (a > b) {
if(a%b==0){
System.out.println(" (答案:" + a / b + ")");
}
else
for (int n = 1; n < b;) {
n++;
m = n;
if (a % n == 0 && b % n == 0) {
a = a / n;
b = b / n;
chufa(a, b);
break;
}
}
if (m == b)
System.out.println(" (答案:" + a + "/" + b + ")");
}
else if (a == b) {
System.out.println(" (答案:" + a / b + ")");
}
else if (a < b) {
for (int n = 1; n < a;) {
n++;
m = n;
if (a % n == 0 && b % n == 0) {
a = a / n;
b = b / n;
chufa(a, b);
break;
}
}
if (m == a)
System.out.println(" (答案:" + a + "/" + b + ")");
}
}
}
}
运行结果截图:
遇到的错误:1没有区分两个随机数的大小情况,导致错误。
2.除法未按分数显示,且计算结果不精确。
个人上课时未能按时完成的原因:思维不够活跃灵敏,对基础知识不熟练,敲击代码的速度太慢。