Click here to Skip to main content
15,896,606 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
C#
int a = 5;
int b = 2;
float c = a/b;
Console.WriteLine(c);

Answer: 2
why answer is 2 it's need to be 2.5 cause answer is assigned to float variable. (or implicit casting need to be done here)
C#
int a = 5;
int b = 2;
float c = (float) a/b;
Console.WriteLine(c);

Answer 2.5

why i need casting?
Posted
Updated 10-Feb-15 1:40am
v2

 
Share this answer
 
When you divide two integers, the result is always an integer.

That's for your first sample...
In your second sample you cast the dividend to float so the division is of float...
 
Share this answer
 
In almost all programming languages there is an implied and automatic conversion between compatible types.
The rule that is normally used is to convert all data types of an expression to the 'supertype' of them. Normally in C all integers will be converted in floats or doubles if thhey are operated against one of them, but this is n ot your case because you are dividing two homogenous types data, two integers. So happen that the code performs an integer division, then in the assignement, where it will found a float, the former result is converted to float (promoted) then assigned.
In the second example you have made a 'cast' forcing the compiler to convert the first integer to float. In this case the division is between two unhomogenous types, which supertype is the float. The compiler then will first convert the divisor to float than perform a floating point division and assign result.
This link describes very well the whole process for many languages.

About your second question I have not understood if you mean "Why I need casting in this piece of code" or "why I need such a feature in the language". In the first case you need to cast it because your expression is an integer expression assigned to a float, so it must be calculated as integere than converted to be assigned. Casting you are telling to the compiler this is a mixed float expression and I want it calculated as float.
For the second case the answer is implicit in the first case.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900