2

所以我正在为一个学校项目编写一个程序,其中一部分需要让用户在命令行中输入一个随机数。然后程序使用 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 << x; 来测试它。它表明 atof 给了我错误的号码。例如,当我在命令行中输入 5.0 作为我的编号时,它显示我的 x 是 379.7465。知道有什么问题吗?

4

2 回答 2

10

你包括 stdlib.h 吗?

我发现如果我不显式导入 stdlib.h 代码符合并运行,但 atof 返回 0,当我包含 stdlib.h 时,它会按预期返回值。

我将 gcc 用于 c 代码。我假设它与 c++ 相同。

于 2011-10-10T03:46:50.333 回答
2

尽管它的名字暗示它返回一个浮点数,但 atof实际上返回一个双精度数。

因此,您必须将其转换为双精度才能使其成为浮点数。

这是一个例子:

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

这非常有效。

于 2011-10-10T03:43:50.280 回答