Objective-C type conversion and objective-c type conversion
Type conversion usually refers to a variable, which is converted from one type to another. For example, to convert a long type to an int type
Use the following method:
(type_name) expression
In Objective-C, we usually use CGFloat for floating point operations. 32 bits are float type, 64 bits are double type, and the conversion method is usually
Follow these steps:
#import <Foundation/Foundation.h>int main(){ int sum = 17, count = 5; CGFloat mean; mean = (CGFloat) sum / count; NSLog(@"Value of mean : %f\n", mean ); return 0;}
The result of the above code compilation and execution:
2013-09-11 01:35:40.047 demo[20634] Value of mean : 3.400000
Here, we will explain that the type conversion priority of a variable is higher than the division, that is, sum is converted to the double type first (64-bit), and division is calculated based on the generated double value.
Type conversion can be implicit and automatically executed by the compiler.
The following code converts the int type to the following code:
#import <Foundation/Foundation.h>int main(){ int i = 17; char c = 'c'; /* ascii value is 99 */ int sum; sum = i + c; NSLog(@"Value of sum : %d\n", sum ); return 0;}
The result of the above code compilation and execution:
2013-09-11 01:38:28.492 demo[980] Value of sum : 116
Sum is 116, because the compiler converts 'C' into ascii values before performing the actual addition operation.
The general data conversion process is generally from low to high. If it is from high to low, data will be lost. As shown in: