C语言 打印浮点值

《C Primer Plus 》例题解析 程序清单3.7 showf_pt.c 程序


/* showf_pt.c -- 以两种方式显示float类型的值 */
#include<stdio.h>
int main(void)
{
	float aboat = 32000.0;
	double abet = 2.14e9;
	long double dip = 5.32e-5;

	printf("%f can be written %e\n", aboat, aboat);
	// 下一行要求编译器支持C99或其中的相关特性
	printf("And it's %a in hexadecrimal, powers of 2 natation\n", aboat);
	printf("%f can be written %e\n", abet, abet);
	printf("%Lf can be written %Le\n", dip, dip);

	return 0;
}

运行结果:

32000.000000 can be written 3.200000e+04
And it's 0x1.f400000000000p+14 in hexadecrimal, powers of 2 natation
2140000000.000000 can be written 2.140000e+09
0.000053 can be written 5.320000e-05

解析:

在C语言中,float类型的数据默认保留小数点后6位,不足6位的以0补齐。

浮点数常量的基本形式:有符号的数字(包括小数点),后面紧跟e/E,最后是一个有符号数表示10的指数。

printf("%f can be written %e\n", aboat, aboat);

%f 是指打印十进制计数法的float和double类型浮点数

%e 是指打印指数计数法的浮点数,指数计数法也叫e计数法

所以输出结果为:

32000.000000 can be written 3.200000e+04
printf("And it's %a in hexadecrimal, powers of 2 natation\n", aboat);

%a / %A 指打印十六进制格式的浮点数

十六进制用0-15表示数字,但是由于没有单独的数表示10-15,所以用字母A-F来表示10-15,所以是:0、1、2、3、4、5、6、7、8、9、A、B、C、D、E、F

十六进制表示浮点型常量格式:在十六进制数前加上十六进制前缀(0x或0X),用p或P分别代替e或E,用2的幂代替10的幂(即:p计数法),如下所示:

0xa.1fp10

十六进制a等于十进制的10,1f 转换为十进制就是(1\times 16^{^{-1}})+(15\times16^{-2}),P10是2^{^{10}},所以0xa.1fp10表示的值是[10+(1\times16^{-1})+(15\times16^{-2})]\times2^{10}(即十进制10364.0)

参照上面十六进制浮点数常量格式,先求出2的幂

32000=2\times(32000\times2^{-1})=2\times16000\\=2^{2}\times(16000\times2^{-1})\\=2^{3}\times(8000\times2^{-1})\\=2^{4}\times(4000\times2^{-1})\\=2^{5}\times(2000\times2^{-1})\\=2^{6}\times(1000\times2^{-1})\\=2^{7}\times(500\times2^{-1})\\=2^{8}\times(250\times2^{-1})\\=2^{9}\times(125\times2^{-1})\\=2^{10}\times(62.5\times2^{-1})\\=2^{11}\times(31.25\times2^{-1})\\=2^{12}\times(15.625\times2^{-1})\\

=2^{13}\times(7.8125\times2^{-1})\\=2^{14}\times(3.90625\times2^{-1})\\=2^{14}\times1.953125

 32000一直除以2,直到出现小于2的数,这样就知道2的幂了

下面把1.953125换成16进制

1.953125=16^{-1}\times(1.953125\times16)\\=16^{-2}\times(31.25\times16)\\=16^{-2}\times500

 15由"f"表示,所以  (500)_{10}=(1f4)_{16}

所以  (1.953125)_{10}=(1.f4)_{16}

所以32000写成十六进制浮点数常量格式就是 0x1.f4p+14

And it's 0x1.f400000000000p+14 in hexadecrimal, powers of 2 natation

受编译器影响,有的运行结果是 0x1.f400000000000p+14,有的是0x1.f4p+14,还有的是0x1.f40000p+14

同理

printf("%f can be written %e\n", abet, abet);
printf("%Lf can be written %Le\n", dip, dip);

输出

2140000000.000000 can be written 2.140000e+09
0.000053 can be written 5.320000e-05

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值