2013-07-16 19 views
1

所以我不得不做出在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); 
    } 

} 

回答

4

則不應使用int類型,請abc係數。如果你使用double類型,你的代碼應該工作。

當您使用整數時,那麼使用b*b4*a*c的代碼很可能會導致整數溢出並拋出您的代碼邏輯。

+0

我明白了,這是有道理的。由於 – Mo2

1

因爲ab,和cint s時,表達式(b*b)4*a*c也計算爲int值。整數的最大可能值爲2,147,483,647或約33,000 x 65,000。

對於一元二次方程,其中分數係數是常見的,你應該使用double

順便說一句,注意,a = 0情況下的解決方案 - 這將使它成爲一個線性方程

+0

我知道這是線性的,但不能使用二次公式來計算,否則你會被0 感謝確切的數字來劃分,雖然,這是有道理的,因爲INT 4個字節的限制。 – Mo2

+0

沒錯,但寫一個實用的方法,當一個很好的目標是使其強大的意想不到的投入。返回'-c/B'比引發錯誤友好很多,除非被叫取決於是否有兩種不同的溶液(其中有即使在二次情況下可能不是)。 –

+0

你是對的,但這僅限於學校作業。 – Mo2