201571030303 小学四则混合元算 龚继恒
源码地址
https://github.com/luchengyi312/GongJiheng2
一、需求分析
1、由用户输入参数n,然后随机产生n道加减乘除练习题,每个数字在 0 和 100 之间,运算符在3个到5个之间;
2、运算过程中不得出现负数与非整数,比如不能出 3/5+2=2.6,2-5+10=7等算式;
3、将学号与生成的n道练习题及其对应的正确答案输出到文件“result.txt”中,文件目录与程序目录一致。
例如:当程序接收的参数为4时,输出如下:

软件附加功能要求如下:
支持有括号的运算式,包括出题与求解正确答案。算式中存在的括号必须大于2个,且不得超过运算符的个数。
扩展程序功能支持真分数的出题与运算,运算时分数需自动化简,比如 1/2+1/6=2/3,而非4/6。
二、设计实现
1、运算结果不能为负数和非整数;
2、将学号与生成的n道练习题及其对应的正确答案输出到文件“result.txt”中。
三、功能实现
我们在
四、测试运行

五、核心代码
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main(String[] args) throws IOException {
File file = new File("result.txt");
FileOutputStream fop = new FileOutputStream(file);
if (!file.exists())
{
file.createNewFile();
}
int x;
System.out.println("输入题目的数量:");
Scanner scan2 = new Scanner(System.in);
x = scan2.nextInt();
String serialNo = "201571030303";
fop.write(serialNo.getBytes());
fop.write("\r\n".getBytes());
for(int i=0;i<x;i++){
int a=(int)(Math.random()*100);
int b=(int)(Math.random()*100);
int c=(int)(Math.random()*100);
String q="";
int ans=0;
int[] flag=new int[2];
for(int j=0;j<2;j++){
int f=(int)(Math.random()*4);
switch(f){
case 0:
if(j==0){
q=a+"+"+b;
}
else{
q=q+"+"+c;
}
flag[j]=0;
break;
case 1:
if(j==0){
q=a+"-"+b;
}
else{
q=q+"-"+c;
}
flag[j]=1;
break;
case 2:
if(j==0){
q=a+"*"+b;
}
else{
q=q+"*"+c;
}
flag[j]=2;
break;
case 3:
if(j==0){
q=a+"/"+b;
}
else{
q=q+"/"+c;
}
flag[j]=3;
break;
}
}
if(flag[0]<2){
if(flag[1]<2){
if(flag[0]==0){
ans=a+b;
}
else{
ans=a-b;
}
if(flag[1]==0){
ans+=c;
}
else{
ans-=c;
}
}
else{
if(flag[1]==2){
ans=b*c;
}
else{
if(c==0){
continue;
}
if(b<c || b%c!=0) {
i=i-1;
continue; }
ans=b/c;
}
if(flag[0]==0){
ans+=a;
}
else{
ans=a-ans;
}
}
}
else{
if(flag[0]==2){
ans=a*b;
}
else{
if(b==0){
continue;
}
if(a<b || a%b!=0) {
i=i-1; //如果出现重新循环
continue; //判断结果不能为负数和非整数
}
ans=a/b;
}
if(flag[1]==0){
ans+=c;
}
else if(flag[1]==1){
ans-=c;
}
else if(flag[1]==2){
ans*=c;
}
else{
if(c==0){
continue;
}
if(ans<c || ans%c!=0) {
i=i-1; //如果出现重新循环
continue; //判断结果不能为负数和非整数
}
ans/=c;
}
}
if(ans<0) //判断结果不能为负数
{
i=i-1; continue;
}
q=q+"="+ans; //用字符串将算式和答案连在一起
System.out.println(q);
fop.write(q.getBytes()); //写入表达式
fop.write("\r\n".getBytes()); //换行
}
fop.close();
}
浙公网安备 33010602011771号