69

My friend is trying to make some kind of calculation as a task for class, and he's having some trouble.

The problem is that he gets an input from the user as int (it has to be, it's a part of the task). He is trying to convert it to double in the code below, but this doesn't work. The results are int anyway.

double firstSolution = ((b1 * a22 - b2 * a12) / (a11 * a22 - a12 * a21));
double secondSolution = ((b2 * a11 - b1 * a21) / (a11 * a22 - a12 * a21));
cottontail
  • 10,268
  • 18
  • 50
  • 51
Samuel E.
  • 2,320
  • 2
  • 26
  • 31

4 Answers4

103

You have to cast one (or both) of the arguments to the division operator to double:

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

Since you are performing the same calculation twice I'd recommend refactoring your code:

double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;

This works in the same way, but now there is an implicit cast to double. This conversion from int to double is an example of a widening primitive conversion.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
  • Just pointing the risk here, `b1 * a22 - b2 * a12` would result in a `int`, same as the determinant. Leading to some calculation error since the cast will be done after the operation in `( )`. – AxelH May 09 '17 at 08:53
46

Converting to double can be done by casting an int to a double:

You can convert an int to a double by using this mechanism like so:

int i = 3; // i is 3
double d = (double) i; // d = 3.0

Alternative (using Java's automatic type recognition):

double d = 1.0 * i; // d = 3.0

Implementing this in your code would be something like:

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

Alternatively you can use a hard-parameter of type double (1.0) to have java to the work for you, like so:

double firstSolution = ((1.0 * (b1 * a22 - b2 * a12)) / (1.0 * (a11 * a22 - a12 * a21)));
double secondSolution = ((1.0 * (b2 * a11 - b1 * a21)) / (1.0 * (a11 * a22 - a12 * a21)));
cottontail
  • 10,268
  • 18
  • 50
  • 51
Reut Sharabani
  • 30,449
  • 6
  • 70
  • 88
13

I think you should casting variable or use Integer class by call out method doubleValue().

user902691
  • 1,149
  • 4
  • 20
  • 46
  • 2
    Casting to `double` from `int` is not possible, but `doubleValue ()` helped me, thanks. – Acuna Aug 30 '18 at 02:11
6

Either use casting as others have already said, or multiply one of the int variables by 1.0:

double firstSolution = ((1.0* b1 * a22 - b2 * a12) / (a11 * a22 - a12 * a21));
sampson-chen
  • 45,805
  • 12
  • 84
  • 81