第四章数据输入与输出.ppt
文本预览下载声明
C语言程序设计;回顾上章:;本章目标:;数据输入输出的概念;(二).C语言本身不提供输入输出语句,输入和输出操作是由C函数库中的函数来实现的
例如:
字符输入函数: getchar 字符输出函数:putchar
格式输入函数: scanf 格式输出函数: printf
字符串输入函数:gets 字数串输出函数:puts
;(三).在使用系统库函数时,要用预编译命令“#include”将有关的“头文件”包括到用户源文件中.
例如:在调用标准输入输出库函数时,文件开头应该有:
#include “stdio.h”(系统到当前目录寻找要包含的文件,找不到,再按标准方式查找)
或:
#include stdio.h(标准方式:系统到存放C库函数头文件的目录中寻找要包含的文件);格式: putchar( c )
参数: c为字符常量、变量或表达式
功能:把字符c输出到显示器上
返值:正常,为显示的代码值;出错,为EOF(-1);
#include stdio.h
main()
{ int c;
char a;
c=65; a=B;
putchar(c); putchar(\n); putchar(a);
};[例4-2 ] 阅读程序
#include stdio.h
main()
{
char c1=A, c2=66 ;
int c3=\103,c4 ;
c4=c3+1;
putchar(c1); putchar(c2);
putchar(\n);
putchar(c3); putchar(c4);
};格式:printf(“格式控制串”,输出表列)
功能:按指定格式向显示器输出数据
返值:正常,返回若干个任意类型的数据;出错,返回EOF(-1);2.函数的使用说明;[例4-3] 阅读程序
#include stdio.h
main( )
{int a=3,b;
printf(a=%d,b=%d\n,a,b=4);
}
其中:
a=%d,b=%d 格式控制字符串
a,b=4 输出表列
%d 格式说明符
“a=” “, ” “b=” 普通字符 ;3. 格式说明符;(1)整型数据;2 o格式符,以8进制数形式输出整数。
o格式符是将内存单元中的各位的值(0或1)按八进制形式输出,因此输出的数值不带符号,即将符号也一起作为八进制数的一部分输出. ;(3)x格式符。以十六进制数形式输出整数。同样不会出
现负的十六进制数。
例: #includestdio.h
void main()
{
int a=-1;
printf(%d,%o,%x\n,a,a);
}
输出结果为:
可以用“%lx”输出长整型数,也可以指定输出字段的宽度
例: “%12x”;(4)u格式符,用来输出unsigned型数据.
一个有符号整数(int 型)也可以用%u格式输出;
一个unsigned 型数据也可以用%d格式输出。
unsigned 型数据也可用%o或%x格式输出。;例4-5 无符号数据的输出。#includestdio.hvoid main(){ unsigned int a=65535;int b=-2;printf(a=%d,%o,%x,%u\n,a,a,a,a);printf(b=%d,%o,%x,%u\n,b,b,b,b);} ;(2)实型数据;例4-6 输出实数时的有效位数。#include stdio.hvoid main(){ float x,y; x=111111.111; y=222222.222; printf(″%f″,x+y);} ;例4-7输出双精度数时的有效位数。#include stdio.hvoid main(){double x,y; x=1111111111111.111111111; y=2222222222222.222222222; printf(%f\n,x+y);} ;例4-8 输出实数时指定小数位数。#includestdio.hvoid main(){ float f=123.456; printf(%f\n%10f\n%10.2f\n%.2f\n%-10.2f\n,f,f,f,f,f);} ;(2)e格式符,以指数形式输出实数。
可用以下形式:
① %e。不指定输出数据所占的宽度和数字部分的小数位数.
例:4-9
#includestdio.h
void main()
{
printf(%e\
显示全部