Atof not working?

Atof not working?

本文关键字:working not Atof      更新时间:2023-10-16

我正在为一个学校项目编写一个程序,其中一部分需要用户在命令行中输入一个随机数。然后程序使用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
}

程序编译了,但是没有正常工作。我通过添加count <<x;结果显示阿托夫给我的号码是错的。例如,在命令行中输入5.0作为我的数字时,它显示我的x是379.7465。知道怎么了吗?

是否包含stdlib.h ??

我发现如果我不显式地导入stdlib.h代码遵守并运行,但是atof返回0,当我包含stdlib.h时,它返回预期的值。

我使用gcc的c代码。我想c++也是一样的

尽管它的名字表明它返回的是浮点数,但实际上返回的是双精度数。

因此,你必须将其强制转换为double类型才能使其成为float类型。

下面是一个例子:

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

这个效果很好