C++中,float double區別
在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