我开发了一个程序来生成随机二次方程并显示它们的解。我从包含从-9到9的数字的数组中取整数,避免0.我使用Random对象选择了索引。但是,我得到了很多无效的方程,因为B的平方变得超过4AC,解决方案不是一个实数,我得到了#N; NaN"作为我的解决方案我想设置一个条件,例如B的平方将始终大于4AC,并且数字将以这种方式从数组中获取。 我的代码是:
import java.util.Random;
class number{
String equation, result;
public void set(){
int[] n = {-9,-8,-7,-6,-5,-4,-3,-2,-1,1,2,3,4,5,6,7,8,9};
Random r = new Random();
int x = r.nextInt(17);
int xx = r.nextInt(17);
int xxx = r.nextInt(17);
int a = n[x];
int b = n[xx];
int c = n[xxx];
double b1 = 0-b; double ac = 4*a*c ; double b2 = b*b; double rt1 = b2-ac;
double rt = Math.sqrt(rt1); double px1 = b1 + rt ; double px2 = b1 - rt;
double a1 = 2*a; double x1 = px1/a1; double x2 = px2/a1;
equation = String.format("The equation is (%d)X^2 + (%d)X + (%d) ",
a,b,c):
result = String.format("Roots are %.3f and %.3f" , x1, x2);
}
public String geteq(){
return equation; }
public String getres(){
return result; }
然后在另一个类中我刚刚在JButton的actionListener类中的JTextField中分配它们。 有没有办法,点击按钮后,它会自动重复set()方法,直到B的平方大于4AC?
答案 0 :(得分:1)
你可以试试这个:
do {
a = n[r.nextInt(17)];
b = n[r.nextInt(17)];
c = n[r.nextInt(17)];
} while (b*b<=4*a*c);
这样,您只能拥有真正的解决方案