在生活中最常使用到的是整數,像是時間和金錢等;有些時候則會使用小數(浮點數),如根號2和圓周率等。整數和浮點數在電腦中各有定義,會根據電腦支援的位元數來限定範圍,一旦超出這個範圍,所得到的數值就沒有意義。
在這裡我想要做個實驗,測試32位元的作業系統中,浮點數所能提供的精準度為何?在C語言中,浮點數又分為float、double、long double,分別為4、8、12 bytes,照理來講,支援越多bytes的型態精準度越高。我以根號2(Square Root of 2)來做測試,而根號2等於1.4142135623730950488…
/**
Theme: Precision & Size of Type
Compiler: Dev C++ 4.9.9.2
Date: 99/12/05
Author: ShengWen
Blog: https://cg2010studio.wordpress.com/
*/
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
int main(){
string a[100];
cin >> a[0];
long double o = sqrt(2);
double p = sqrt(2);
float q = sqrt(2);
cout << fixed;//fix fraction number
for(int i = 0; i < 20; i++){//print long double
cout.precision(i);
cout << o << endl;
}
for(int i = 0; i < 20; i++){//print double
cout.precision(i);
cout << p << endl;
}
for(int i = 0; i < 20; i++){//print float
cout.precision(i);
cout << q << endl;
}
cout << sizeof(long double) << endl;
cout << sizeof(double) << endl;
cout << sizeof(float) << endl;
cout << "-----" << endl;
cout << sizeof(a) << endl;//string array
cout << sizeof(a[0]) << endl;//string element
cout << sizeof(0) << endl;//int
cout << sizeof(.0) << endl;//double
cout << sizeof(sizeof(.0)) << endl;
system("pause");
return EXIT_SUCCESS;
}
結果為:
1234567
1
1.4
1.41
1.414
1.4142
1.41421
1.414214
1.4142136
1.41421356
1.414213562
1.4142135624
1.41421356237
1.414213562373
1.4142135623731
1.41421356237310
1.414213562373095
1.4142135623730951
1.41421356237309510
1.414213562373095100
1.4142135623730951000
1
1.4
1.41
1.414
1.4142
1.41421
1.414214
1.4142136
1.41421356
1.414213562
1.4142135624
1.41421356237
1.414213562373
1.4142135623731
1.41421356237310
1.414213562373095
1.4142135623730951
1.41421356237309510
1.414213562373095100
1.4142135623730951000
1
1.4
1.41
1.414
1.4142
1.41421
1.414214
1.4142135
1.41421354
1.414213538
1.4142135382
1.41421353817
1.414213538170
1.4142135381699
1.41421353816986
1.414213538169861
1.4142135381698608
1.41421353816986080
1.414213538169860800
1.4142135381698608000
12
8
4
—–
400
4
4
8
4
請按任意鍵繼續 . . .
由long double、double、float分別列印從精準度0到19,可見三者精準度皆不到小數點後19位(long double和double精準度皆在小數點後15位數,float則在小數點後7位數),可以比較根號2=1.4142135623730950488…。雖然說離小數點越遠的數字越不值錢,但卻在某些場合會是決定成敗的一個關鍵要素!我寫過ACM的題目,不只是考驗演算法跟資料結構的熟悉度,更考驗對C語言的瞭解度,曾經卡在精準度上很懊惱……如果精準度不夠,就算差了麼一丁點兒,發射到宇宙的太空船也許會因為這樣而悄悄消失在銀河系之中XD~
另外測試了sizeof()函式,如上所述float、double、long double,分別為4、8、12 bytes。而C語言預設,整常數型態為int,浮點常數型態為double。
參考維基百科:Square Root of 2。

Comments on: "[C++] 型態的精準度和大小 (Precision and Size of Type)" (1)
[…] 改用double之後問題就解決了,哈~其實沒有,再去想想為什麼吧!其實之前有寫精準度 (Precision)和型態的精準度和大小(Precision and Size of Type),連過去看看,就會更瞭解精準度的問題! […]
讚讚