# puts 与 printf

puts 是 output string 的缩写，只能用来输出字符串，不能输出整数、小数、字符等，我们需要用另外一个函数，那就是 printf。

printf 比 puts 更加强大，不仅可以输出字符串，还可以输出整数、小数、单个字符等；输出格式也可以自己定义，例如：

* 以十进制、八进制、十六进制形式输出；
* 要求输出的数字占 n 个字符的位置；
* 控制小数的位数。

printf 是 print format 的缩写，意思是“格式化打印”。这里所谓的“打印”就是在屏幕上显示内容，与“输出”的含义相同，所以我们一般称 printf 是用来**格式化输出**的。

**先来看一个简单的例子：**

```c
printf("C语言");
```

这个语句可以在屏幕上显示“C语言”，与`puts("C语言");`的效果类似。

输出变量 abc 的值：

```c
int abc=999;
printf("%d", abc);
```

这里就比较有趣了。先来看`%d`，**d 是 decimal 的缩写，意思是十进制数**，%d 表示以十进制的形式输出。输出什么呢？输出变量 abc 的值。%d 与 abc 是对应的，也就是说，会用 abc 的值来替换 %d。

再来看个复杂点的：

```c
int abc=999;
printf("The value of abc is %d !", abc);
```

会在屏幕上显示：

```
The value of abc is 999 !
```

再来看：

```c
int a=100;
int b=200;
int c=300;
printf("a=%d, b=%d, c=%d", a, b, c);
```

会在屏幕上显示：

```
a=100, b=200, c=300
```

再次证明了 %d 与后面的变量是一一对应的，第一个 %d 对应第一个变量，第二个 %d 对应第二个变量……

## 格式控制符

* %d：以十进制形式输出一个整数。
* %c：输出一个字符。c 是 character 的简写。
* %s：输出一个字符串。s 是 string 的简写。
* %f：输出一个小数。f 是 float 的简写。

### 各种整数的输出

1\)输出 int 使用`%d`，输出 short 使用`%hd`，输出 long 使用`%ld`

2\) 输出十进制使用`%d`，输出八进制使用`%o`（注意是字母 o，不是数字 0），输出十六进制使用`%x`或`%X.`

2\) 输出十进制使用`%d`，输出八进制使用`%o`（注意是字母 o，不是数字 0），输出十六进制使用`%x`或`%X`。如果希望带上前缀，可以加`#`，例如 %#d、%#o(8进制)、%#x(16进制)、%#X (16进制)。


---

# 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/puts-yu-printf.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.
