在C++中,printf函数是从C语言继承而来的,用于格式化输出。printf函数的参数传递和解析遵循以下规则:
printf函数的第一个参数是一个格式化字符串(format string),后续参数是需要输出的变量或值。这些参数会按照格式化字符串中的占位符(placeholder)进行匹配。#include<iostream>
using namespace std;
int main() {
int a = 5;
float b = 7.5;
const char* s = "Hello, World!";
printf("Integer: %d, Float: %.2f, String: %s\n", a, b, s);
return 0;
}
%d:整数(int)%f:浮点数(float/double)%s:字符串(const char*)%c:字符(char)%x/%X:十六进制整数(int)%o:八进制整数(int)%e/%E:科学计数法表示的浮点数(float/double)%g/%G:自动选择合适的浮点数表示方式(float/double)占位符中还可以包含修饰符,例如:
-:左对齐+:显示正负号0:前导零填充空格:正数前加空格,负数前加负号.:指定小数点后的位数*:宽度或小数点位数为变量值#include<iostream>
using namespace std;
int main() {
int a = -123;
float b = 3.14159;
printf("Left aligned: %-10d\n", a);
printf("Always show sign: %+d\n", a);
printf("Leading zeros: %06d\n", a);
printf("Space for positive numbers: % d\n", a);
printf("Fixed decimal places: %.2f\n", b);
printf("Variable width and precision: %*.*f\n", 8, 2, b);
return 0;
}
注意:在C++中,更推荐使用std::cout进行格式化输出,因为它提供了类型安全和更好的错误处理。printf函数在C++中仍然可用,但通常不是首选方法。