我一直在嘗試天花板函數,並得到了一些奇怪的結果。如果我執行一個小數乘以百的小數運算,我會得到一定的結果。但是,如果我直接執行該乘法的結果ceil,我會得到一個完全不同的輸出。另一個轉折是,這些不同的結果只出現在某些數字上。任何幫助,將不勝感激。C++天花板函數的奇怪結果
#include <stdio.h>
#include <cmath>
int main()
{
cout << "The ceiling of " << 411 << " is " << ceil(411) << endl;
cout << "The ceiling of 4.11*100 is " << ceil(4.11*100) << endl;
cout << "The ceiling of " << 121 << " is " << ceil(121) << endl;
cout << "The ceiling of 1.21*100 is " << ceil(1.21*100) << endl;;
}
OUTPUT:
The ceiling of 411 is 411
The ceiling of 4.11*100 is 412
The ceiling of 121 is 121
The ceiling of 1.21*100 is 121
但即使我使用double也會發生同樣的情況。這一直髮生在一些數字上,但不會發生在別人身上,這真的讓我感到困惑。 – sowmya 2011-04-06 07:07:23
@sowmya:偶數是浮點數。 'float'類型的精度低於'double'類型。這意味着,'雙'更精確地存儲*比較*,但這並不意味着它代表它「準確地」。事實上,'double'就是這樣命名的,因爲它是雙精度浮點數。看到這個:http://en.wikipedia.org/wiki/Double_precision_floating-point_format – Nawaz 2011-04-06 07:09:28
你在示例代碼中使用'double'。那裏沒有使用'浮動'號碼。 – 2011-04-06 07:13:04