Automatic type conversion or forced type conversion can be performed based on the storage space occupied by data types. The general principle is that the data type of small storage capacity can be automatically converted to the Data Type of large storage capacity.
Different types of data are automatically converted from left to right (from low to high) according to the following relationship,
_ Bool, Char, short int, enumeration type-> int-> long-> float-> double-> long double.
If these data types are mixed, the different types of data in the operation are first converted to the same type, and then the operation is performed. The conversion is automatically converted from left to right, as shown in Table 2-3.
Table 2-3 type conversion sequence table
Operand 1 Type |
Operand 2 type |
Converted type |
_ Bool, Char, short int, and enumeration type |
Int |
Int |
_ Bool, Char, short int, enumeration type, int |
Long int |
Long int |
_ Bool, Char, short int, enumeration type, Int, long int |
Long long |
Long long |
_ Bool, Char, short int, enumeration type, Int, long int, long |
Float |
Float |
_ Bool, Char, short int, enumeration type, Int, long int, long, float |
Double |
Double |
_ Bool, Char, short int, enumeration type, Int, long int, long, float, double |
Long double |
Long double |
If there is the following expression, where F is of the float type, I is of the int type, L is of the long int type, and S is of the short int type, what type is the result?
F * I + L/s
The running result is of the float type, because f is another float operand and float operation. The result is of the float type.
If the type conversion is followed by the right-to-left condition, the forced type conversion is required. The syntax of the forced type conversion is simple, that is, to add (the target type) before the data ), however, such conversions are risky and may cause data loss. Therefore, proceed with caution. For example:
Long int L = 6666666666;
Nslog (@ "L = % Li", L );
Int I = (INT) L;
Nslog (@ "I = % I", I );
The result of running is that the 6666666666 value has exceeded the capacity of the int type, so data loss occurs.
L = 6666666666
I =-1923267926
Forced conversion is sometimes embedded in other expressions. It is intertwined with the running priority, and the situation becomes more complex. Suppose there are the following statements:
Int Total = 3446;
Int n = 6;
Float average = total/N;
The result of running the float variable average is 574, And the decimal point content is truncated. If we use the following statement:
Int Total = 3446;
Int n = 6;
Float average = (float) Total/N;
The average of the variable whose float is completed is 574.333, which is more accurate than the above calculation. This is because (float) Total first converts the total variable of the int type to the total variable of the float type.