计算结果不正确

时间:2015-11-04 21:50:41

标签: java math equation

我写了以下代码

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.0.0)”, 虽然它应该是“(-4.0,4.5)”。 我试图找出为什么这种情况发生了一段时间,但我找不到任何理由。我发现我的计算公式是正确的。

问题出在哪里?

1 个答案:

答案 0 :(得分:3)

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

/是整数除法,因为使用的/个操作数均为int类型。整数除法产生一个整数值,即使其结果稍后被分配给double。将/个操作数转换为double以获得double分区。 (Equ2single声明相同。)