我开发了一个程序来生成随机二次方程并显示它们的解。我从包含从 -9 到 9 的数字的数组中获取整数,避免使用 0。我使用 Random 对象选择索引。但是,我经常得到无效的方程,因为 B 的平方变得大于 4AC,解不是实数,我得到“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?
最佳答案
你可以试试这个:
do {
a = n[r.nextInt(17)];
b = n[r.nextInt(17)];
c = n[r.nextInt(17)];
} while (b*b<=4*a*c);
这样,你才能得到真正的解决方案
关于java - 以实数为根生成随机二次方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49776393/