c++ format 例子
时间: 2024-01-31 19:37:52 浏览: 14
以下是一些C语言格式化输出的例子:
1. 输出整数:
```c
int num = 10;
printf("My favorite number is %d", num);
```
输出结果:My favorite number is 10
2. 输出浮点数:
```c
float pi = 3.1415926;
printf("The value of pi is %.2f", pi);
```
输出结果:The value of pi is 3.14
3. 输出字符:
```c
char letter = 'A';
printf("The first letter of the alphabet is %c", letter);
```
输出结果:The first letter of the alphabet is A
4. 输出字符串:
```c
char name[20] = "John";
printf("My name is %s", name);
```
输出结果:My name is John
5. 输出十六进制数:
```c
int hex = 0x2B;
printf("The value of hex is %X", hex);
```
输出结果:The value of hex is 2B
6. 输出指针地址:
```c
int *ptr = #
printf("The address of num is %p", ptr);
```
输出结果:The address of num is 0x7ffd8a5b5c9c
7. 输出多个变量:
```c
int age = 25;
float height = 1.75;
char gender = 'M';
printf("I am %d years old, %.2f meters tall, and my gender is %c", age, height, gender);
```
输出结果:I am 25 years old, 1.75 meters tall, and my gender is M
注意:在格式化输出中,%表示占位符,后面的字母表示要输出的数据类型,如%d表示输出整数,%f表示输出浮点数,%c表示输出字符,%s表示输出字符串,%X表示输出十六进制数。.2表示保留两位小数。%p表示输出指针地址。在输出多个变量时,需要按照顺序依次写出每个变量的格式。