2010-11-29 31 views
0

我調試我的代碼時感到驚訝。在這裏,我提供了示例代碼不完全從雙轉換爲int - 似乎問題是在CPU指令

#include<QMessageBox> 
#include<iostream> 
#include<math.h> 
#include<QApplication> 
using namespace std; 

class MyMessageBox: public QMessageBox 
{ 
    public: 
     MyMessageBox(string message,QWidget *parent=0) : 
      QMessageBox(
       QMessageBox::NoIcon, 
       QString("ErrorMessage"), 
       QString(message.c_str()), 
       QMessageBox::Ok, 
       parent, 
       Qt::Widget) 
     { 
     } 
}; 

void Hai() 
{ 
    int tempi = 4; 
    double a = pow(10,tempi); 
    int temp = int(pow(10,tempi)); 

    //int temp=a; 

    MyMessageBox mb1((QString::number(pow(10,tempi))+ 
         " *** "+ 
         QString::number(temp)).toStdString()); 
    mb1.exec(); 
} 

int main(int argc, char * argv[]) 
{ 

    QApplication app(argc,argv); 
    Hai(); 

    return app.exec(); 
} 

,其結果是,

10000 *** 9999 

而主要的一點是,這個事情發生僅用於電源4(= POW(X,4),不爲任何其它權力

編輯:

我試圖使用Visual Studio最少的代碼,但它產生萬正好但是,它從來沒有編譯,直到我做了C型。明確地反轉。下面的代碼給出

#include<iostream> 
#include<math.h> 

using namespace std; 

void Hai() 
{ 
    int tempi = 4; 
    double a=pow(10.0,tempi); 
    int temp=pow(10.0,tempi); 

    cout << " a " << a << " temp " << temp << endl ; 
} 

int main(int argc, char * argv[]) 
{ 
    Hai(); 
    return 1; 
} 
+0

請儘量舉例說明。你的例子包含一堆與任何東西無關的QT cruft - 一個使用printf()的10行程序也會顯示問題。 – 2010-11-29 06:51:40

+1

@j_random_hacker請參閱編輯 – prabhakaran 2010-11-29 07:35:25

回答

2

你的問題是,你的浮點運算的結果是9999.9999999 ...所以int(...)int(9999.9999999...)其中,當然,是9999以來的浮點運算很少是準確的,你不要寫你的代碼來期待它們。在這種情況下,您可以使用舍入功能。

正如在評論中指出的那樣,您的pow(10,4)的實現不會產生正整數的可能性極小,因此您的示例可能存在缺陷。然而,這一點仍然存在:不要指望浮點結果是準確的。

參見:why is 1.2 * 30 = 35?

0

記住POW(10,4)和POW(10.0,4)和POW(10.0,4.0)不會調用相同的功能。

0

沒有標準保證了pow函數的準確性。負責任的圖書館供應商試圖獲得像這樣簡單的確切案例,但如果你想編寫出色的可移植代碼,你不能依賴這個(如你的經驗所示)。

如果您需要精確計算小整數冪,請使用重複乘法(或用於此目的的庫函數)計算它們,而不是調用pow