所以我不得不做出在Java程序來解決的「X」用求根公式的值,這包括虛和實數。問題是,我的代碼似乎並沒有給出正確的結果爲以下3個值:二次規劃Java返回錯誤結果
a=10,000
b=75,000
c=35,000
它返回小整數正確的價值觀,但是。任何想法爲什麼?我認爲它與double的數據類型有關,但我不確定。
注意,要求包括該輸入是整型的唯一
我相信正確的結果是-7.0和-0.5,但我收到想象的結果。由於
這裏是我的代碼:
package QuadRootsInt;
import java.util.Scanner;
/**
*
* @author
*/
public class QuadRootsInt {
/**
* Instance variables
*/
private double realNumb;
private double imagNumb;
private double finalRoot1;
private double finalRoot2;
/**
*
* @param a a value of binomial
* @param b b value of binomial
* @param c c value of binomial
*/
public QuadRootsInt(int a, int b, int c){
if(a==0){
System.out.println("Cannot divide by zero...system is exisitng.");
System.exit(0);
}
}
/**
* Evaluating the square root part of the formula and updates the right variable accordingly
* @param a first coefficient of binomial
* @param b second coefficient of binomial
* @param c third coefficient of binomial
*/
public void getRoot(int a, int b, int c){
if((b*b)<4*a*c){
imagNumb=Math.sqrt(Math.abs(Math.pow(b,2)-4*a*c));
double realFinal1=((-b)/(2.0*a));
double imagFinal1=(imagNumb/(2.0*a));
double realFinal2=((-b)/(2.0*a));
double imagFinal2=(imagNumb/(2.0*a));
System.out.println("The solutions to the quadratic are: " + realFinal1+"+"+"i"+imagFinal1 + " and " + realFinal2+"-"+"i"+imagFinal2);
}
else {
realNumb=Math.sqrt(Math.pow(b, 2)-4*a*c);
finalRoot1=((-b)+realNumb)/(2*a);
finalRoot2=((-b)-realNumb)/(2*a);
System.out.println("The solutions to the quadratic are: " + finalRoot1 + " and " + finalRoot2);
}
}
/**
* Main Method - Testing out the application
* @param args
*/
public static void main(String args[]){
Scanner aCoef = new Scanner(System.in);
System.out.print("Enter the 'a' coefficient: ");
int aInput = aCoef.nextInt();
Scanner bCoef = new Scanner(System.in);
System.out.print("Enter the 'b' coefficient: ");
int bInput = bCoef.nextInt();
Scanner cCoef = new Scanner(System.in);
System.out.print("Enter the 'c' coefficient: ");
int cInput = cCoef.nextInt();
QuadRootsInt quadTest = new QuadRootsInt(aInput, bInput, cInput);
quadTest.getRoot(aInput, bInput, cInput);
}
}
我明白了,這是有道理的。由於 – Mo2