> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/computer-basics/type-conversion.md).

# 数据类型转换

### 为什么需要转换

不同数据类型之间进行运算或赋值时，会发生类型转换，分为**隐式转换**和**强制转换**。

### 隐式类型转换（自动）

按照“由低到高”的方向自动进行，不会丢失精度：

```
bool → char → short → int → long long → float → double
```

```cpp
int a = 3;
double b = a;      // int 自动转 double，3.0
cout << 5 / 2.0;   // 2.5，int 与 double 运算，int 转为 double
```

### 强制类型转换（显式）

当需要把高精度转成低精度，或控制计算方式时使用：

```cpp
int a = 7, b = 2;
cout << a / b << endl;              // 3，整数除法
cout << (double)a / b << endl;      // 3.5，先转 double

double x = 3.9;
cout << (int)x << endl;             // 3，直接截断取整，不四舍五入
```

> 常见坑：`5 / 2` 结果是 2 而不是 2.5，因为两个整数相除结果是整数。需要写 `5 / 2.0` 或强制转换。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/computer-basics/type-conversion.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
