Home > Software design >  Simple Algebra Math in Java Showing Wrong Answer. Pls Help (Student)
Simple Algebra Math in Java Showing Wrong Answer. Pls Help (Student)

Time:04-17

I am using this code in BlueJ for my school project but this is returning wrong answer - I have tried everything but each time i enter this value - A = 1, B = 2 and C = 3, it is showing 1 as answer which is incorrect.

 import java.util.*;
 public class ABCD
 {
 public static void ABCTest() {
 double a, b, c;
 Scanner inputNumber = new Scanner(System.in);
 System.out.println("Enter the value of A, B and c");
 
 a = inputNumber.nextInt();
 b = inputNumber.nextInt();
 c = inputNumber.nextInt();
 
 double aSquare = a*a;
 double bSquare = b*b;
 double cSquare = c*c;
 
 double ax = (1/aSquare);
 double bx = (1/bSquare);
 double cx = (1/cSquare);
 
 double x = (1/a*a)   (2/b*b)   (3/c*c);
 System.out.println("Value of x is: "   x);
 
 System.out.println("Value of A square is: "   aSquare);
 System.out.println("Value of B Square is: "   bSquare);
 System.out.println("Value of C square is: "   cSquare);
 
 System.out.println("Value of A divide is: "   ax);
 System.out.println("Value of B divide is: "   bx);
 System.out.println("Value of C divide is: "   cx);
 
 
 

} }

CodePudding user response:

Intellij Input/Output:

Enter the value of A, B and c
1
2
3
Value of x is: 6.0
Value of A square is: 1.0
Value of B Square is: 4.0
Value of C square is: 9.0
Value of A divide is: 1.0
Value of B divide is: 0.25
Value of C divide is: 0.1111111111111111

Code is fine.

UPDATE

You probably expected the value of x to be equal to sum of these

Value of A divide is: 1.0
Value of B divide is: 0.25
Value of C divide is: 0.1111111111111111

But you are wrong. Because in statement:

double x = (1/a*a)   (2/b*b)   (3/c*c);

If a = 1, then (1/1*1) means first it divides 1 with 1 which is equal to 1, then multiplies 1 with 1, which is equal to 1.

The same with b and c, because you assign values of 2 and 3 to them.

In the end 1 2 3=6

CodePudding user response:

In Java, there is operation priority that determines the order of calculations. I changed the code and it will work correctly:

double a, b, c;
    Scanner inputNumber = new Scanner(System.in);
    System.out.println("Enter the value of A, B and c");

    a = inputNumber.nextInt();
    b = inputNumber.nextInt();
    c = inputNumber.nextInt();

    double aSquare = a*a;
    double bSquare = b*b;
    double cSquare = c*c;

    double ax = (1/aSquare);
    double bx = (1/bSquare);
    double cx = (1/cSquare);

    double x = (1/aSquare)   (2/bSquare)   (3/cSquare);
    System.out.println("Value of x is: "   x);

    System.out.println("Value of A square is: "   aSquare);
    System.out.println("Value of B Square is: "   bSquare);
    System.out.println("Value of C square is: "   cSquare);

Value of x is: 1.8333333333333333

  •  Tags:  
  • java
  • Related