khuang8493
7/10/2018 - 12:04 AM

Variable Types Convert in C

Converting Variable Types in calculation in C.

I have two int variables I need to divide to get a float.

Code:
int a=6;
int b=4;
float c=a/b;

This code keeps giving me 1, and I need 1.5.

Code:
int a=6;
int b=4;
float c=(float)a/(float)b;

Technically, it's sufficient to cast one side to float, e.g.:
Code:
float c=(float)a/b;

The rules in C and C++ is that if one side is floating point, the other side is converted to float by default. 

***Make sure not use the wrong syntax when casting. Change:

float(n)

to

(float)n