私はJavaにかなり慣れていないので、二次式を単純化するコードを書くのに助けが必要です. 現在、私のプログラムは 2 つの解を小数点以下 2 桁に切り捨てています。しかし、判別式の二乗を単純化する方法がわかりません。たとえば、判別式が 8 の場合、プログラムは 2√2 を出力します。これを行うために必要なコードを教えてください。
package quadraticprogram;
//This imports the DecimalFormat class, Scanner class, and all other Java classes.
import java.text.DecimalFormat;
import java.util.Scanner;
import java.util.*;
public class QuadraticProgram {
public static void main(String[] args) {
int a, A;
Scanner scan = new Scanner (System.in);
System.out.println ("Use integer value, enter minimum value of a:");
a = scan.nextInt();
System.out.println ("Use integer value, enter maximum value of A:");
A = scan.nextInt();
Random generator = new Random();
// Generate random integers in the range from a to A
// and assign them to numa, numb, and numc
double numa = generator.nextInt(A - a + 1) + a;
double numb = generator.nextInt(A - a + 1) + a;
double numc = generator.nextInt(A - a + 1) + a;
System.out.println ("numa" + numa);
System.out.println ("numb" + numb);
System.out.println ("numc" + numc);
// Define d as the discriminant and take its square root
double d;
d = ((numb*numb)-(4*numa*numc));
double r = Math.sqrt(d);
// Calculate the two solutions
double s = ((-numb + r)/(2*numa));
double S = ((-numb - r)/(2*numa));
// Truncate the two solutions to two decimal places.
DecimalFormat fmt = new DecimalFormat ("0.##");
// If the discriminant is negative there are no real solutions.
if (d<0) {
System.out.println("No Real Solutions");
} else {
// Print both solutions if the discriminant is not negative
System.out.print(fmt.format(s));
System.out.println("," + fmt.format(S));
}
}
}
現在、プログラムはユーザーに最小整数 a と最大整数 A を入力させています。次に、a と A の間のランダムな double 値 numa、numb、および numc が生成されます。次に、プログラムは判別式 d を次のように計算します。ダブル。次に、d の平方根を取ります。これが r です。次に、プログラムは 2 つの解 s と S の計算を終了します。判別式が 0 以上の場合、プログラムは 2 つの解を出力し、小数点以下 2 桁まで切り捨てます。