所以我正在为一个学校项目编写一个程序,其中一部分要求用户在命令行输入一个随机数。程序然后使用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&lt;&lt;来测试它了。 X;并且它表明atof给了我错误的号码。例如,当将5.0作为我的号码放入命令行时,它显示我的x是379.7465。知道什么是错的吗?
答案 0 :(得分:9)
你是否包括stdlib.h ??
我发现如果我没有显式导入stdlib.h代码符合并运行,但是atof返回0,当我包含stdlib.h时它会返回预期的值。
我使用gcc作为c代码。我假设它与c ++相同。
答案 1 :(得分:2)
即使它的名字暗示它返回一个浮点数,atof 实际上会返回一个双精度数。
所以,你必须将它强制转换成双精度才能成为浮点数。
以下是一个例子:
float value = (float)atof(argv[1]);
printf("%.2f + 3 = %.2f", value, (value + 3));
这完美无缺。