Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to convert an int variable to double [duplicate]

Tags:

java

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!

like image 429
Samuel E. Avatar asked Nov 06 '12 14:11

Samuel E.


People also ask

Can we change int to double?

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 .

How do you convert int to double in Python?

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.

Can we convert int to double in C?

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 .


1 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.

like image 193
Mark Byers Avatar answered Oct 08 '22 03:10

Mark Byers