[英]Strange static cast behaviour in a member function of class used as template parameter
在用作模板參數的類的成員函數中,我有一個包含以下代碼的函數:
double x = /*Something operation returning double*/;
x /= CubeWidth; /*CubeWidth is a class member*/
cout << "Element after centering and normalization = " << x << endl;
cout << "and after adding 1 and truncating = " << x+1 << endl;
cout << "then static cast = " << (int) x+1 << endl;
這個函數的輸出是
Element after centering and normalization = 1
and after adding 1 and truncating = 2
then static cast = 1
顯然,最后一行應給出答案2。
如果我實例化完全相同的類而不使用它作為模板參數,我不會得到這個打印輸出,而是我有正確的。
誰能告訴我為什么會這樣?
很可能x
(一個雙0.9999999...
)不完全是1
,它是0.9999999...
通過打印x==1.0
或x<1.0
檢查其確切值,看看究竟是什么。 或者在輸出中添加更多數字:
cout << "and after adding 1 and truncating = " << setprecision( 15 ) << x+1 << endl;
舍入為整數將丟棄逗號后的所有數字,因此1.999999...
變為1
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.