printf() 函数定义在 stdio.h 头文件中。它有助于将结果输出到控制台。它向 stdout 流提供格式化输出。
int printf(const char *format, ...); #where format can be a integer, character, string, float
printf() 函数将格式字符串作为参数。格式标签原型是 %[flags][width][.precision][length]specifier.
其中说明符可以是 - c, d 或 i, e, E, f, g, G, o, s, u, x, X, P, n, %
标志可以是 - +, -, (空格), #, 0
宽度可以是 - (数字), *
精度可以是 - .数字, .*
长度可以是 - h, l, L
| 参数 | 描述 | 必需/可选 |
|---|---|---|
| 格式 | 包含要写入 stdout 流的文本的字符串 | 必需 |
| 附加参数 | 包含一个值,用于替换格式参数中指定的每个 %-tag | 可选 |
printf() 函数的返回值为成功时写入字符的总数,失败时为负数。
| 输入 | 返回值 |
|---|---|
| 如果成功, | 字符总数 |
| 失败时 | 一个负数 |
#include <stdio.h>
int main()
{
int year = 5;
float page = 2.1;
/* Display the results using the appropriate format strings for each variable */
printf("ontest.com is over %d years old and pages load in %.1f seconds.\n", year, page);
return 0;
}
输出
ontest.com is over 5 years old and pages load in 2.1 seconds
#include <stdio.h>
int main (){
char char = 'P';
char strg[25] = "ontest.com";
float flt = 8.102;
int num = 100;
int no = 150;
double dble = 15.123456;
printf("Character is %c \n", char);
printf("String is %s \n" , strg);
printf("Float value is %f \n", flt);
printf("Integer value is %d\n" , num);
printf("Double value is %lf \n", dble);
printf("Octal value is %o \n", no);
printf("Hexadecimal value is %x \n", no);
return 0;
}
输出
Character is P String is ontest.com Float value is 8.102 Integer value is 100 Double value is 15.123456 Octal value is 226 Hexadecimal value is 96