0

I wrote the following code

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 + ")");
            }
       }  
   }

The result recieve for inserting "1 2 3 4 5 6" is "(-4.0,4.0)", While it is supposed to be "(-4.0,4.5)". I have tried to figure out why this happens for a while now but I cannot find any reason. I find my calculation formula correct.

Where is the problem?

roamner
  • 3
  • 1
  • 2
    `int/int` is still `int` and integer doesn't have fraction part. If you need type which can handle fractions use `double` (also as operands). – Pshemo Nov 04 '15 at 21:52

1 Answers1

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

/ is the integer division as both / operands used are of type int. An integer division yields an integer value even if its result is later assigned to a double. Cast the / operands to double to get a double division. (Same for Equ2single declaration.)

ouah
  • 142,963
  • 15
  • 272
  • 331