C语言printf()用法的8个实例
C语言中的 printf() 是一个强大而灵活的输出函数,它允许程序员以各种格式输出数据。printf() 函数的基本语法如下:
printf("格式化字符串", 参数1, 参数2, ...);
格式化字符串中的占位符用于指定输出的格式,而后面的参数则对应这些占位符。让我们从简单的例子开始,逐步深入。
1. 基本输出
最简单的 printf() 用法是直接输出一个字符串:
#include <stdio.h> int main() { printf("Hello, World!"); return 0; }
输出结果:
Hello, World!
2. 输出整数
要输出整数,我们使用 %d 占位符:
#include <stdio.h> int main() { int age = 25; printf("I am %d years old.", age); return 0; }
输出结果:
I am 25 years old.
3. 输出浮点数
对于浮点数,我们可以使用 %f 占位符。默认情况下,它会显示 6 位小数:
#include <stdio.h> int main() { float pi = 3.14159; printf("The value of pi is %f", pi); return 0; }
输出结果:
The value of pi is 3.141590
如果我们想控制小数点后的位数,可以在 % 和 f 之间加上.n
,其中 n 是想要显示的小数位数:
printf("Pi to two decimal places: %.2f", pi);
输出结果:
Pi to two decimal places: 3.14
4. 输出字符
对于单个字符,我们使用 %c 占位符:
#include <stdio.h> int main() { char grade = 'A'; printf("I got an %c in the exam.", grade); return 0; }
输出结果:
I got an A in the exam.
5. 输出字符串
字符串使用 %s 占位符:
#include <stdio.h> int main() { char name[] = "Alice"; printf("Hello, %s!", name); return 0; }
输出结果:
Hello, Alice!
6. 多个占位符的使用
printf() 函数可以同时使用多个占位符:
#include <stdio.h> int main() { char name[] = "Bob"; int age = 30; float height = 1.75; printf("%s is %d years old and %.2f meters tall.", name, age, height); return 0; }
输出结果:
Bob is 30 years old and 1.75 meters tall.
7. 格式化输出的宽度控制
我们可以控制输出的宽度,例如,%5d 表示输出一个占据至少 5 个字符宽度的整数,右对齐:
#include <stdio.h> int main() { int num1 = 123, num2 = 12345; printf("%5d\n%5d\n", num1, num2); return 0; }
输出结果:
123 12345
如果想左对齐,可以在宽度说明符前加一个减号:
printf("%-5d\n%-5d\n", num1, num2);
输出结果:
123 12345
8. 特殊字符的输出
有时我们需要输出一些特殊字符,如换行符 \n 或制表符 \t:
#include <stdio.h> int main() { printf("Line 1\nLine 2\nLine 3\n"); printf("Column 1\tColumn 2\tColumn 3"); return 0; }
输出结果:
Line 1 Line 2 Line 3 Column 1 Column 2 Column 3
通过这些示例,我们可以看到 printf() 函数的多样性和灵活性。