int i1 = 10;
int i2 = 4;
float g = (float)i1 / i2; //here you want to tell the division op to do floating division
cout<<g<<endl;
second blockstatic_cast<float>(i1); //change to float
static_cast<float>(i2); //change to float
g = i1/i2; //get int instead of float
cout<<g<<endl;
Hi Jaybob I don't understand this particular response. Can you tell me more abt (float) i1/i2?
Is the result of int i1 and int i2 converted to float once they are divided?
I guess it really comes down to understanding why an integer can't be promoted to a float. fixed the above error
You can promote an int to a float, but you have to realize how it happens.
Promotion of one type to another involves creating temporary anonymous variables. In static_cast<float>(i1), you create a temporary float value and assign it the value from i1. The type of i1 never changes. i1 was, is and will always be an int. However, an unnamed float value initialized with i1's value is available and must be used or assigned before the end of the statement.
In the case of float g = 10/4, you have to look at operator precedence. The division operator happens before the assignment operator. So, the compiler divides 10 (int) by 4 (int). Because both operands are integers, the compiler performs integer division, and creates a temporary integer value with the result (2). Then the assignment occurs, and the float value g is assigned the temporary value, and ends up with the value 2.0.
Great - got most of it. Plz look at this other example of newbie exemble:
int foo
float goo
float g
g = foo / goo.
The division operator happens before the assignment operator.
so int/float (before operator assignment) = ?
In the case where you are using literal values (such as 10, or 4), replacing one or both of the integer literal value with a floating point literal value (10.0 or 4.0) will cause both operands to be converted to floating point values, and the division will be done using floating point math.
Got it but why?
Also when should I be using the f suffix for my floats?
Final question: can you permanently change a var type? For e.g. int to float, where the variable is now permanently float without using typecast