在VC++6.0平台,一定记住
float:有效数字位数7位。
double:有效数字位数7位。
小数的时候小数点占一位;

类型 比特数 有效数字 数值范围
float 32 6-7 -3.4*10(-38)~3.4*10(38)
double 64 15-16 -1.7*10(-308)~1.7*10(308)
long double 128 18-19 -1.2*10(-4932)~1.2*10(4932)
简单来说,Float为单精度,内存中占4个字节,有效数位是7位(因为有正负,所以不是8位),在我的电脑且VC++6.0平台中默认显示是6位有效数字;double为双精度,占8个字节,有效数位是16位,但在我的电脑且VC++6.0平台中默认显示同样是6位有效数字(见我的double_float文件)
还有,有个例子:在C和C++中,如下赋值语句
float a=0.1;
编译器报错:warning C4305: 'initializing' : truncation from 'const double ' to 'float '
原因:
在C/C++中(也不知道是不是就在VC++中这样),上述语句等号右边0.1,我们以为它是个float,但是编译器却把它认为是个double(因为小数默认是double),所以要报这个warning,一般改成0.1f就没事了。
本人通常的做法,经常使用double,而不喜欢使用float。
上代码吧:
#include <iostream>
using namespace std;

int main ()
{
// 数字定义
short s;
int i;
long l;
float f;
double d;

// 数字赋值
s = 10;
i = 1000;
l = 1000000;
f = 310.12347121;
d = 310.12347121;

// 数字输出
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;

return 0;
}结果:

short s :10
int i :1000
long l :1000000
float f :310.123
double d :310.123

#include <iostream>
using namespace std;
int main()
{

short s;
int i;
long l;
float f;
double d;

// 数字赋值
s = 10.001;
i = 10.001;
l = 10.904554544501;
f = 10.04554544501;
d = 10.04543546565401;

// 数字输出
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;
return 0;
}结果:

short s :10
int i :10
long l :10
float f :10.0455
double d :10.0454


#include <iostream>
using namespace std;

int main ()
{
// 数字定义
short s;
int i;
long l;
float f;
double d;

// 数字赋值
s = 10;
i = 1000;
l = 1000000;
f = 230.47;
d = 30949.374;

// 数字输出
cout << "short s :" << s << endl;
cout << "int i :" << i << endl;
cout << "long l :" << l << endl;
cout << "float f :" << f << endl;
cout << "double d :" << d << endl;

return 0;
}结果:

short s :10
int i :1000
long l :1000000
float f :230.47
double d :30949.4