C语言的格式化输出359
在C语言中,格式化输出语句用于按指定的格式向屏幕或文件输出数据。它由printf()和scanf()函数组成,其中printf()用于输出数据,scanf()用于从标准输入设备(通常是键盘)读取数据。
printf()函数
printf()函数的语法如下:int printf(const char *format, ...);
其中:* format:指定输出格式的字符串
* ...:可选的附加参数,根据format中指定的格式提供要输出的数据
format字符串由以下字符组成:* 转换说明符:以百分号开始(%),后面跟一个字符,指定数据类型的格式化方式。
* 格式限定符:可选的,用于指定输出的特定格式。
* 宽度字段:可选的,指定输出内容的最小宽度。
* 精度字段:可选的,指定浮点数的小数位数或字符串的最大长度。
转换说明符
常用的转换说明符有:* %c:字符
* %d:有符号十进制整数
* %i:有符号十进制整数(与%d等效)
* %f:双精度浮点数
* %lf:长双精度浮点数
* %s:字符串
格式限定符
常用的格式限定符有:* -:左对齐
* +:始终显示符号(对于数字)
* 0:用零填充
* 空格:对于非负数字,显示一个空格符号
示例
#include
int main() {
int age = 25;
char name[] = "John Doe";
printf("My name is %s and my age is %d.", name, age);
return 0;
}
输出:My name is John Doe and my age is 25.
scanf()函数
scanf()函数的语法如下:int scanf(const char *format, ...);
其中:* format:指定输入格式的字符串
* ...:可变数量的指针,指向要存储输入数据的变量
format字符串的语法与printf()函数类似,但它包含输入转换说明符,而不是输出转换说明符。
输入转换说明符
常用的输入转换说明符有:* %c:字符
* %d:有符号十进制整数
* %i:有符号十进制整数(与%d等效)
* %f:双精度浮点数
* %lf:长双精度浮点数
* %s:字符串
示例
#include
int main() {
int age;
char name[20];
printf("Enter your name: ");
scanf("%s", name);
printf("Enter your age: ");
scanf("%d", &age);
printf("Hello, %s. You are %d years old.", name, age);
return 0;
}
输出:Enter your name: John Doe
Enter your age: 25
Hello, John Doe. You are 25 years old.
2024-11-21
上一篇:C 语言字符串库函数:全面指南
下一篇:C 语言比较字符串函数
Java方法栈日志的艺术:从错误定位到性能优化的深度指南
https://www.shuihudhg.cn/133725.html
PHP 获取本机端口的全面指南:实践与技巧
https://www.shuihudhg.cn/133724.html
Python内置函数:从核心原理到高级应用,精通Python编程的基石
https://www.shuihudhg.cn/133723.html
Java Stream转数组:从基础到高级,掌握高性能数据转换的艺术
https://www.shuihudhg.cn/133722.html
深入解析:基于Java数组构建简易ATM机系统,从原理到代码实践
https://www.shuihudhg.cn/133721.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html