The C language provides two types of type conversion: implicit conversion (automatic) and explicit conversion (manual). Explicit conversion methods include the cast operator (type), sprintf()/sscanf() functions, atoi()/atof() functions, and strtol()/strtod() functions. Note that explicit conversions may result in data loss or loss of precision, and the special operator * applies to pointer types.
Type conversion in C language
C language provides two types of conversion: implicit conversion and Explicit conversion.
Implicit conversion
When two different types of data need to be operated, the compiler will automatically convert the low-precision data type to a high-precision data type . For example:
<code class="c">int a = 5; float b = 2.5; float c = a + b; // a 会隐式转换为 float</code>
Explicit conversion
When you need to manually convert one data type to another data type, you can use the cast operator(type)
. For example:
<code class="c">int a = 5; float b = (float)a; // a 显式转换为 float</code>
In addition to cast, there are several other explicit type conversion methods:
Example
Suppose we have an integer variablea and a floating point variable
b. We can use the following code for type conversion:
<code class="c">// 使用强制类型转换将 b 转换为 int int c = (int)b; // 使用 sprintf() 函数将 a 转换为字符串 char str[10]; sprintf(str, "%d", a); // 使用 atoi() 函数将 str 转换为 int int d = atoi(str);</code>
Note
.
The above is the detailed content of How to perform type conversion in c language. For more information, please follow other related articles on the PHP Chinese website!