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)); 2 4 Answers
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.
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.0Alternative (using Java's automatic type recognition):
double d = 1.0 * i; // d = 3.0Implementing 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))); I think you should casting variable or use Integer class by call out method doubleValue().
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));