[英]Generating random math questions
我们必须制定一个程序,然后针对不同年级生成数学问题,因此它们的难度会有所不同。 我们必须在最小和最大边界内产生2个随机数。 然后,我们必须使这两个数字进行运算。 例如,将它们加在一起,或彼此除以或相乘等等。
该程序根据用户提供的年份级别工作。 每年的级别具有不同的最小和最大数量,以及不同的操作。 例如。 1年仅是加减法,而7年是加减乘除法,依此类推。 我定义了不同的方法来帮助我做到这一点,但是我似乎无法让我的程序生成我想要的东西。 它看起来应该像下面的图片一样。 我的部分代码在这里。 当我运行程序时,它只会生成多个整数(10或20,具体取决于用户选择尝试的数学问题数)。 它不会在数字之间产生任何运算,例如(+,-,/,x)
有人能指出我做错了正确的方向吗?
private static void generateQuestion(int yearLevel) {
int min = getMin(yearLevel);
int max = getMax(yearLevel);
int num1 = (int) (min + (max - min) * Math.random());
int num2 = (int) (min + (max - min) * Math.random());
int oper = getOper(yearLevel);
String result = " ";
char op;
switch (oper) {
case 1:
op = '+';
result = (num1 + num2 + " ");
break;
case 2:
op = '-';
result = (num1 - num2 + " ");
break;
case 3:
op = '*';
result = (num1 * num2 + " ");
break;
case 4:
op = '/';
result = (num1 / num2 + " ");
break;
case 5:
op = '%';
result = (num1 % num2 + " ");
break;
}
;
}
private static int getMin(int yearLevel) {
int min = 0;
if (yearLevel == 0 || yearLevel == 1 || yearLevel == 2 || yearLevel == 3 || yearLevel == 4) {
min = 0;
}
if (yearLevel == 5 || yearLevel == 6) {
min = -999;
}
if (yearLevel == 7) {
min = -9999;
}
return min;
}
private static int getMax(int yearLevel) {
int max = 9;
if (yearLevel == 0 || yearLevel == 1 || yearLevel == 2 || yearLevel == 3 || yearLevel == 4) {
max = 9;
}
if (yearLevel == 5 || yearLevel == 6) {
max = 999;
}
if (yearLevel == 7) {
max = 9999;
}
return max;
}
public static int getOper(int yearLevel) {
yearLevel = 0;
int opBounds = 1;
if (yearLevel == 1 || yearLevel == 2) {
opBounds = 2;
}
if (yearLevel == 3 || yearLevel == 4 || yearLevel == 5) {
opBounds = 4;
}
if (yearLevel == 7) {
opBounds = 5;
}
return opBounds;
}
}
我是一个像您一样的初学者,我将再选一堂课Question,以容纳所产生的谜语和正确的结果。 然后在你的
private static Question generateQuestion(int yearLevel) {
Question out=new Question();
...
//build string for selected case, for example
String answer=num1+" / "+num2;
double result=num1/num2; //rather use double
out.answer=answer; //String field
out.result=result;
return out;
}
然后通过显示问题并将其与预期结果进行比较来进行处理。
您已将result声明为String并尝试在其中添加数字,则无法这样做。
所以这段代码:
String result = " ";
char op;
switch (oper) {
case 1:
op = '+';
result = (num1 + num2 + " ");
break;
case 2:
op = '-';
result = (num1 - num2 + " ");
break;
更改为以下内容:
int result = 0;
char op;
switch (oper) {
case 1:
op = '+';
result = (num1 + num2);
break;
case 2:
op = '-';
result = (num1 - num2);
break;
然后,您将必须使用Java方法(例如“ Integer.toString(int i)”)来打印出整数结果(示例)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.