C # type conversion tutorial,
C # type conversion
Sometimes it is really necessary to put different types of values together for calculation, such as: 3.5 + 8 what should we do at this time? There are two situations:
Automatic type conversion:
For two different types of data operations, the low-precision type is automatically converted to a higher-precision type.
Taking 3.5 + 8 as an example, it is clear that the precision of the number 8 is low (int), while that of the number 3.5 is high (double). Therefore, 8 is automatically converted to the double type, that is, convert to 3.5 + 8.0 for calculation, and the result is 11.5.
See this example:DoubleD = 2; the accuracy of 2 is obviously lower than the precision of the variable d, SO 2 will be automatically converted to 2.0 and then assigned to d.
Let's look at this example again:IntI = 3.0; the accuracy of variable I is less than 3.0, but because I has been declared as an int type variable, the value of the variable can be changed, butTypeIt cannot be changed, so this command willError.
Forced type conversion:
Cannot be automatically converted to the required type. You can use forced type conversion. For example, the preceding example can be completed as follows:
int i=(int)3.0;
The (int) before the number indicates that the destination type of the conversion is int, and 3.0 is forcibly converted to 3.
Note that,If the double type is forcibly converted to the int type, the fractional part is lost.For example, if (int) 2.8, we get 2.