printf scanf的用法
时间: 2024-10-20 11:01:21 浏览: 40
`printf` 和 `scanf` 是C语言中的两个标准库函数,分别用于输出数据到控制台(格式化打印)和从控制台读取数据。
1. **printf**(“printf”是"print formatted"的缩写):
用于格式化输出数据。基本语法是:`printf(format_string, argument_list)`。`format_string` 中包含占位符 `%d`, `%f`, `%s`等,它们代表整数、浮点数和字符串,`argument_list`则是对应的变量或值。例如:
```c
int num = 42;
float pi = 3.14;
char name[] = "Tom";
printf("My number is %d, and PI is %.2f, my name is %s.\n", num, pi, name);
```
2. **scanf**(“scan formatted”的缩写):
用于从标准输入(通常是键盘)读取数据,并将其赋值给指定的变量。基本语法是:`scanf(format_string, variable_list)`。`format_string` 的模式匹配输入的数据,`variable_list` 是需要接收输入的变量名。比如:
```c
int num;
float pi;
char name[20];
printf("Enter an integer: ");
scanf("%d", &num); // 输入整数并存储在num中
printf("Enter a float: ");
scanf("%f", &pi); // 输入浮点数并存储在pi中
printf("Enter your name: ");
scanf("%s", name); // 读取字符串并存储在name中,注意字符串前的'\0'
```
阅读全文
相关推荐
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)