2

私は学校のプロジェクト用のプログラムを書いていますが、その一部では、ユーザーがコマンド ラインで乱数を入力する必要があります。次に、プログラムは atof を使用して数値を float に変換し、それを使って計算できるようにします。プログラムのその部分は次のようになります。

#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 << x; を追加してテストしました。そして、atof が間違った番号を与えていることがわかりました。たとえば、私の番号として 5.0 をコマンド ラインに入力すると、私の x は 379.7465 であることが示されました。何が問題なのですか?

4

2 に答える 2

10

stdlib.h を含めていますか??

stdlib.h を明示的にインポートしない場合、コードは準拠して実行されますが、atof は 0 を返します。stdlib.h を含めると、期待どおりの値が返されます。

私はcコードにgccを使用しています。C++でも同じだと思います。

于 2011-10-10T03:46:50.333 に答える
2

その名前は float を返すことを示唆していますが、atofは実際には double を返します。

そのため、浮動小数点になるには、それを double にキャストする必要があります。

次に例を示します。

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

そして、これは完全に機能します。

于 2011-10-10T03:43:50.280 に答える