Java 随机生成二次算子并生成答案
最编程
2024-04-20 18:52:05
...
如图,这是....Java课上的一个作业,emm
不太想解释怎么写了,涉及到的文件操作,可以看这篇
Java 最实用的文件读写
/**
* @Title: shu.java
* @Description: TODO
* @author 菱形继承
* @date 2020-03-10 10:34:39
*/
package a;
/**
* @ClassName: shu
* @Description: TODO
* @author 菱形继承
* @date 2020-03-10 10:34:39
*/
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.OutputStream;
import java.util.Scanner;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
public class shengcheng {
public static void main(String[] args) throws IOException {
File file= new File("C:\Users\ASUS\Desktop\Java\2020 3 10\src\a\result.txt");
PrintStream ps = new PrintStream("C:\Users\ASUS\Desktop\Java\2020 3 10\src\a\shengcheng.txt");
Writer out = new FileWriter(file);
int c;
Scanner sc=new Scanner(System.in);
System.out.print("请输入题目个数:");
int tg=sc.nextInt();
System.out.print("请输入操作数的范围(如 100,1000等):");
int tf=sc.nextInt();
System.out.println("请选择是否有负数:1:有 0:没有");
int zf=sc.nextInt();
System.out.println("请选择是否包含*或者/:2:否 4:是 ");
int fu=sc.nextInt();
System.setOut(ps);
for(int i=0;i<tg;i++) {//循环控制题目个数
//第一个操作数的选择
int a=(int)(Math.random()*tf);
if(zf==1) {//有负数
int p=(int) (Math.random()*2);
switch(p) {
case 0:a=a*(-1);//取负数
System.out.print(a);break;
case 1:
System.out.print(a);break;
}
}
if(zf==0)System.out.print(a);
else{//选择两个字符‘+’‘-’
int k=(int)(Math.random()*2);
switch(k) {//随机选择运算符
case 0:System.out.print("+");
break;
case 1:System.out.print("-");
break;
}
int b=(int)(Math.random()*(tf-a));
while(b>a)b=(int)(Math.random()*(tf-a));
if(zf==1) {//有负数
int p=(int) (Math.random()*2);
switch(p) {
case 0:b=b*(-1);//取负数
System.out.print(b);break;
case 1:
System.out.print(b);break;
}
}
else System.out.print(b);
System.out.println("=");
String huanhang="rn";
if(k==0)
{
c=a+b;
out.write( Integer.toString(c)+huanhang);
}
else {c=a-b; out.write( Integer.toString(c)+huanhang);}
}
if(fu==4) {//四个字符的‘+’‘-’‘*’‘/’
int k=(int)(Math.random()*4+1);
switch(k) {//随机选择运算符
case 1:System.out.print("+");break;
case 2:System.out.print("-");break;
case 3:System.out.print("*");break;
case 4:System.out.print("/");break;
}
//第二个操作数的选择
int b=(int) (Math.random()*tf+1);
if(zf==1) {//有负数
int p=(int) (Math.random()*2);
switch(p) {
case 0:b=b*(-1);//取负数
System.out.print(b);break;
case 1:
System.out.print(b);break;
}
}
if(zf==0) System.out.print(b);
System.out.println("=");
if(k==1) {
c=a+b;out.write(c);
}
if(k==2) {
c=a-b;out.write(c);
}
if(k==3) {
c=a*b;out.write(c);
}
if(k==4) {
c=a/b;out.write(c);
}
}
}out.close();
}
}
上一篇: 3-2 年级数学寒假作业总结