2011-10-10 83 views
2

所以我正在爲一個學校項目編寫一個程序,其中一部分需要用戶在命令行中輸入一個隨機數。該程序然後使用atof將該數字轉換爲浮點數,以便我可以對它進行一些數學運算。該計劃的一部分是這樣的:Atof無法正常工作?

#include <iostream> 
#include <cstdlib> 
#include "bmplib.h" //this is just something the prof. gave us to help read the image 
#include <cmath> //i might use this later in the program 

#define nummethods 2 
using namespace std; 

unsigned char input[256][256][3]; 
unsigned char bg [256][256][3]; 
unsigned char output[256][256][3]; 
unsigned char m[2][256][256]; 

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

    int h,i,j,k; 
    double x,y,z; 

    //code to read img here and make sure user puts correct number of arguments in 
//command line 

    for (i=0;i<256;i++){ 
    for(k=0;k<3;k++){ 
     y = y + input[i][0][k]; 
    } 
    } 

cout >> y >> endl; //this is giving me 36,164,75 which in RGB is green  

x = atof(argv[3]); //the number was the 3rd thing typed in at the command line 
cout << x << endl; 

z = x + y; //this isn't the exact program, but you get the idea 
cout << z << endl; 

//there's some more code after this written by the prof. that manipulates the image, 
//but i don't think its relevant since it does not use the argv[3] value 
} 

程序編譯,但它沒有工作的權利。我通過添加一個cout來測試它;這表明atof給了我錯誤的號碼。例如,當將5.0作爲我的號碼放入命令行時,它顯示我的x是379.7465。任何想法有什麼不對?

+2

你能把它縮小到最小的情況嗎?例如,執行'atof(argv [1])'並使用'./program 5.0'來試用它,看看你得到了什麼 –

+0

你把頭文件放到atof中了嗎?測試用例會有幫助 – eran

+3

也可以嘗試'cout << argv [3]'。它可能不是你想要的。 – stardt

回答

2

雖然它的名字暗示它返回一個浮點數,但是atof 實際上返回一個double。

所以,你必須將它轉換成雙精度,才能成爲浮點數。

下面是一個例子:

float value = (float)atof(argv[1]); 
printf("%.2f + 3 = %.2f", value, (value + 3)); 

這完美的作品。

+0

雖然你可能在根本原因上是正確的,但是將「double」投射到「float」並不能保證精確度的安全。答案是使用'double' –

+0

@BrianRoach:我不相信double 5.0的最接近的表示是379.7465 float。 – Dani

+0

@Dani - 嘿,就是這樣。手指比腦子快,我應該睡一覺。然而,從雙重到浮動部分的鑄造仍然存在。 (真正的問題在於OP沒有發佈的代碼) –

9

你是否包含stdlib.h?

我發現如果我沒有明確導入stdlib.h代碼符合並運行,但atof返回0,當我包含stdlib.h時,它返回值如預期。

我使用gcc的c代碼。我假設它對於C++來說是一樣的。

+2

這可能是C中類似問題的一個可能原因,但在C++中,函數原型是必需的。當試圖在C++中使用'atof'時,未能包含'stdlib.h'會導致編譯器錯誤。 –