# 数据类型转换

数据类型转换就是将数据（变量、表达式的结果）从一种类型转换到另一种类型。例如，为了保存小数你可以将`int`类型的变量转换为`double`类型。

数据类型转换的一般格式为：

```c
(type_name) expression
```

`type_name`为要转换到的数据类型，`expression`为表达式。例如：

```c
(float) a;  //把a转换为实型
(int)(x+y);  //把x+y的结果转换为整型
(float) 100;  //将一个常量转换为实型,浮点数
```

【示例】将整数转换为浮点数：

```c
#include <stdio.h>
int main(){
   int sum = 17, count = 5;
   double mean;
   mean = (double) sum / count;
   printf("Value of mean : %f\n", mean);
   return 0;
}
```

运行结果：

```
Value of mean : 3.400000
```

需要注意的是，类型转换运算符`( )`的优先级高于`/`，`(double) sum / count`会先将 sum 转换为 double 类型，然后再进行除法运算。如果写作`(double) (sum / count)`，那么运行结果就是 3.000000。

这种由程序员显式进行的转换称为**强制类型转换**。除了强制类型转换，在不同数据类型的混合运算中编译器也会隐式地进行数据类型转换，称为**自动类型转换**。

自动类型转换遵循下面的规则：

1. 若参与运算的数据类型不同，则先转换成同一类型，然后进行运算。
2. 转换按数据长度增加的方向进行，以保证精度不降低。例如int型和long型运算时，先把int量转成long型后再进行运算。
3. 所有的浮点运算都是以双精度进行的，即使仅含float单精度量运算的表达式，也要先转换成double型，再作运算。
4. char型和short型参与运算时，必须先转换成int型。
5. 在赋值运算中，赋值号两边的数据类型不同时，需要把右边表达式的类型将转换为左边变量的类型。如果右边表达式的数据类型长度比左边长时，将丢失一部分数据，这样会降低精度。

下图表示了类型自动转换的规则：

![](/files/-LfnTHxIZa0dHztanlAG)

【示例】自动数据类型转换。

```php
#include<stdio.h>
int main(){
    float PI=3.14159;
    int s1, r=5;
    double s2;
    s1 = r*r*PI;
    s2 = r*r*PI;
    printf("s1=%d, s2=%f\n", s1, s2);
    return 0;
}
```

运行结果：

```
s1=78, s2=78.539753
```

在计算表达式`r*r*PI`时，r 和 PI 都转换成double类型，表达式的结果也为double类型。但由于 s1 为整型，所以赋值运算的结果仍为整型，舍去了小数部分。

> 注意是将小数部分直接丢掉，而不是按照四舍五入向前舍入。

无论是强制转换或是自动转换，都只是为了本次运算的需要而对变量的数据长度进行的临时性转换，而不改变数据说明时对该变量定义的类型。请看下面的例子：

```c
#include<stdio.h>
int main(){
    float f=5.75;
    printf("(int)f=%d, f=%f\n",(int)f, f);
    return 0;
}
```

运行结果：

```
(int)f=5, f=5.750000
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/c/ji-chu/shu-ju-lei-xing-zhuan-huan.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
