Mike Hirt
Mike Hirt

Reputation: 11

How to make a int answer into a float

I have to make the output of an the equation a = x * 9 / y into a float when both 'x' and 'y' are int's. For example x=64 y= 227 but when input that to the equation I get 2 instead of a decimal answer.

How I have it coded:

int y = 227;
int x = 64;
Float a;
a = x * 9 / y;

Upvotes: 1

Views: 1034

Answers (5)

Grijesh Chauhan
Grijesh Chauhan

Reputation: 58281

You need typecast to float:

a = (float)x * (float)9 / (float)y;

Don't know what language you are using but I am writing with respect to C Language.

What I did is called Explicit Casting.

Explicit Casting (given transformation) of data types has higher priority then automatic transformation.

Syntax:  

    (data_type) operand

Where Operand can be variable or phrase.

What @yBee answered.
He is using concept of Implicit Casting by changing 9 to 9.0f in you expression (x * 9.0f) become float and float dived by int again give float.

To understand this you need to know automatic type casting:

Implicit Casting (automatic transformation) works in a way that a variable (operand) of data type that is smaller in length (than data type of second variable) (operand), transforming internally to variable of data type with longer number length. It may sound mixed up, but here is an example:

short int -> int -> unsigned int -> long int -> unsigned long int -> float -> double -> long double

What @Alexei Levenkov doing is?
using both techniques. First convert x into float by Explicit Casting then calculation happens in float due to Implicit Casting.

Actually both answers are better then my answer.

Upvotes: 1

Nobody
Nobody

Reputation: 159

An easy way is to just multiply the end result by 1.0. This will convert it for you.

Upvotes: 0

Thilina Chamath Hewagama
Thilina Chamath Hewagama

Reputation: 9040

Ok, to get a decimal answer when you device any number by an integer number, the right hand side must be a float or double. It's like this

10/3 = 3

10/3.0 = 3.34

got it ?

in your case what you can do is,

int y = 227; 
int x = 64;
Float a = x * 9 / (float)y;

Upvotes: 0

Alexei Levenkov
Alexei Levenkov

Reputation: 100545

In most languages having at least one element in expression of type "float" will make whole expression of type float:

  a = x * 9.0 / y;

You can also cast some mebers explicitly (depending on languge syntax):

 a = (Float)x * 9 / y;

Note that if priorities of operations are not the same (i.e. + and * in the same expression) you may pay close attention to what you want to cast. Following expressions are likely to produce different results (as first one will do x/9 as integers and only then cast it to "float"):

 a = x / 9 + (Float)y;
 a = (Float)x / 9 + y; 

Upvotes: 1

Ryszard Dżegan
Ryszard Dżegan

Reputation: 25434

One of the number should be of type float in order to valid casting: a = x * 9.0f / y;

Upvotes: 2

Related Questions