My friend is trying to make some kind of calculation as a task for class, and he's having some trouble... I hope you can help him.
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));
If you need more explanation, I'll ask him for it. Thanks in advance!
double c = a; Here, the int type variable is automatically converted into double . It is because double is a higher data type (data type with larger size) and int is a lower data type (data type with smaller size). Hence, there will be no loss in data while converting from int to double .
You need to cast one of the terms to a floating point value. Either explicitly by using float (that is ratio = float(a)/b or ratio=a/float(b) ) or implicitly by adding 0.0 : ratio = (a+0.0)/b . If using Python 2 you can from __future__ import division to make division not be the integral one but the float one.
The %d format specifier expects an int argument, but you're passing a double . Using the wrong format specifier invokes undefined behavior. To print a double , use %f .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With