printf 用法 -回复
"printf 用法" 指的是 C/C++ 中的一个函数,用于按照指定格式将数据打印输出。
在 C/C++ 中,printf 函数位于 stdio.h 头文件中,其基本语法如下:
int printf(const char *format, ...);
其中,format 参数为格式控制字符串,指定了输出的格式;后续的参数根据格式控制字符串的要求进行逐个输出。
接下来,我们将详细解释 printf 函数的用法,并给出一些示例。
1. 基本用法:使用 printf 输出文本
-
printf 函数可以输出简单的文本。示例:
c
#include <stdio.h>
int main() {
    printf("Hello, World!");
    return 0;
}
输出:
Hello, World!
2. 格式控制符:输出变量
-
通过格式控制符可以输出变量。常用的格式控制符有:d(整数)、f(浮点数)、s(字符串)、c(字符)等。示例:
c
#include <stdio.h>
int main() {
    int age = 25;
    float height = 1.75;
    char name[] = "John";
    printf("My name is s, I'm d years old and .2f meters tall.", name, age, height);
    return 0;
printf函数是如何实现的}
输出:
My name is John, I'm 25 years old and 1.75 meters tall.
3. 格式控制符:宽度和精度
-
格式控制符还可以指定输出的宽度和精度。示例:
c
#include <stdio.h>
int main() {
    int quantity = 10;
    float price = 5.5;
    printf("The total cost is: 10.2f", quantity * price);