“浮动"与“双精度" [英] 'float' vs. 'double' precision

查看:33
本文介绍了“浮动"与“双精度"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代码

float x  = 3.141592653589793238;
double z = 3.141592653589793238;
printf("x=%f
", x);
printf("z=%f
", z);
printf("x=%20.18f
", x);
printf("z=%20.18f
", z);

会给你输出

x=3.141593
z=3.141593
x=3.141592741012573242
z=3.141592653589793116

输出的第三行 741012573242 是垃圾,第四行 116 是垃圾.双打总是有 16 位有效数字,而浮动总是有 7 位有效数字吗?为什么双打没有 14 位有效数字?

where on the third line of output 741012573242 is garbage and on the fourth line 116 is garbage. Do doubles always have 16 significant figures while floats always have 7 significant figures? Why don't doubles have 14 significant figures?

推荐答案

C 中的浮点数使用 IEEE 754 编码.

Floating point numbers in C use IEEE 754 encoding.

这种类型的编码使用一个符号、一个有效数和一个指数.

This type of encoding uses a sign, a significand, and an exponent.

由于这种编码,许多数字都会有小的变化以允许它们存储.

Because of this encoding, many numbers will have small changes to allow them to be stored.

此外,有效数字的数量可能会略有变化,因为它是二进制表示,而不是十进制表示.

Also, the number of significant digits can change slightly since it is a binary representation, not a decimal one.

单精度(浮点数)为您提供 23 位有效数、8 位指数和 1 个符号位.

Single precision (float) gives you 23 bits of significand, 8 bits of exponent, and 1 sign bit.

双精度 (double) 为您提供 52 位有效数、11 位指数和 1 个符号位.

Double precision (double) gives you 52 bits of significand, 11 bits of exponent, and 1 sign bit.

这篇关于“浮动"与“双精度"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆