C++浮点型分三种:float(单精度)、double(双精度)、long double(扩展精度)。
三者的区别是表示有效数字的范围不同。
数据类型 | 占用空间 | 有效数字范围 |
float | 4字节 | 7位有效数字 8位 |
double | 8字节 | 15~16位有效数字 17位 |
long double | 不少于double | 不低于double 17位 |
注意:
- 在VS和Linux中,long double占用的内存空间分别是8和16字节。
- 有效数字包括了小数点前面和后面的数字。
- C++缺省显示6位有效数字,如果要显示更多的有效数字,可以用printf()函数。
- 浮点数的存储方法和整数不一样,比较复杂,如无必要,不用研究。(百度“为什么浮点数的小数位很多”、“为什么浮点数不精确”)
- 在实际开发中,用整数代替浮点数,整数的运算更快,精度更高。9223372036854775807
示例:
#include <stdio.h> // 使用printf函数需要包含这个头文件。
#include <iostream> // 包含头文件。
using namespace std; // 指定缺省的命名空间。
int main()
{
// float 7位有效数字;double 15~16位有效数字;long double 不低于double
float aa = 1234.45f; cout << "aa=" << aa << endl;
double bb = 12345123056789.45; cout << "bb=" << bb << endl;
long double cc = 12345126789.459; cout << "cc=" << cc << endl;
printf("aa=%lf\n", aa);
printf("bb=%lf\n", bb);
printf("cc=%lf\n", cc);
}