| |||||||||
![]() |
|
|
«
Previous Thread
|
Next Thread
»
|
Thread Tools | Search this Thread | Display Modes |
|
#1
|
|||
|
|||
|
Another Tutorial Question
Right-O.
I was presented with this code: void main() { float a; a=10/3; printf("%f\n",a); } Then, later on in the text, they say this: You do typecasting in C by placing the type name in parentheses and putting it in front of the value you want to change. Thus, in the above code, replacing the line a=10/3; with a=(float)10/3; produces 3.33333 as the result because 10 is converted to a floating point value before the division. My question is, since variable a is already declared a float, why on God's green earth would you need to use a=(float)10/3. The text says you will get a different output this way. Why? Lastly, please excuse the noobness of my questions, but in order for me to effectively learn something, I need to understand the why of things, and not simply the how. RathMon |
|
#2
|
|||
|
|||
|
Math is done on the right side of the assignment first. So if you do not cast, it will do 10 / 3. Since 10 and 3 are both integers, you will get an integer result: 3. The 0.3333333 is truncated. Then, it assigns that to a float value, and so the result will be 3.000000.
You do not need to do (float) 10 / 3, but simply 10.0 / 3. 10.0 is read as a double, which can be assigned to a float. You can also do 10.0f / 3, which is taking a float value 10, and dividing by 3. |
![]() |
| Viewing: Dev Articles Community Forums > Programming > C/C++ Help > Another Tutorial Question |
| Thread Tools | Search this Thread |
| Display Modes | Rate This Thread |
|
|
|
|
|