[英]Generating random quadratic equations imposing condition for real numbers as roots
我設計了一個程序來生成隨機二次方程並顯示其解。 我從包含從-9到9的數字的數組中獲取整數,避免使用0。我通過使用Random對象選擇了index。 但是,當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);
這樣,您只能擁有真正的解決方案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.