2015-11-04 130 views
0

我寫下面的代碼不正確的計算結果

import java.util.Scanner; 

public class Equations 
    { 
     public static void main (String [] args) 
     { 
      Scanner scan = new Scanner (System.in); 
      System.out.println ("This program solves a system of 2 linear equations" +"\n"+ 
      "Enter the coefficients a11 a12 a21 a22 b1 b2:"); 
      int a11 = scan.nextInt(); 
      int a12 = scan.nextInt(); 
      int a21 = scan.nextInt(); 
      int a22 = scan.nextInt(); 
      int b1 = scan.nextInt(); 
      int b2 = scan.nextInt(); 

      System.out.println ("Eq: " + a11 + "*x1" + "+" + a12 + "*x2 = " + b1); 
      System.out.println ("Eq: " + a21 + "*x1" + "+" + a22 + "*x2 = " + b2); 

      if(((a11*a22)-(a12*a21))!=0){ 
       double Equ1single = ((b1*a22)-(b2*a12))/((a11*a22)-(a12*a21)); 
       double Equ2single = (((b2*a11)-(b1*a21)))/(((a11*a22)-(a12*a21))); 
       System.out.println ("Single solution: (" + Equ1single + "," + Equ2single + ")"); 
      } 
     } 
    } 

結果收到用於插入 「1 2 3 4 5 6」 是 「(-4.0,4.0)」, 雖然被認爲是「( -4.0,4.5)」。 我試圖弄清楚爲什麼會發生一段時間,但我找不到任何理由。我發現我的計算公式是正確的。

問題在哪裏?

+2

「int/int」仍然是「int」,整數沒有小數部分。如果你需要可以處理分數的類型,使用'double'(也作爲操作數)。 – Pshemo

回答

3
double Equ1single = ((b1*a22)-(b2*a12))/((a11*a22)-(a12*a21)); 

/是整數除法的同時使用/操作數都是int類型。即使結果稍後分配給double,整數除法也會產生整數值。將/操作數投射到double以獲得double分部。 (與​​聲明相同。)