Atof not working?
Atof not working?
我正在为一个学校项目编写一个程序,其中一部分需要用户在命令行中输入一个随机数。然后程序使用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));
这个效果很好
相关文章:
- GDB - strcmp not working: __strcmp_sse2_unaligned
- QT qScriptConnect is not working
- QDesktopServices::openUrl() not working Qt
- "Configure: Error: Could Not Find a Working Compiler, See config.log For Details"
- C++ std::set ordering not working with customer class*
- C++ SetWindowText not working
- visual studio 2012 c++ hello world - iostream not working
- getGravity not working?
- Opencv findcontours CV_RETR_EXTERNAL not working
- c++ srand() not working
- std::queue::empty() not working?
- BCB swprintf not working
- 将类型作为指向另一个类的对象的指针的泛型类-NOT WORKING
- LoadLibrary is not working
- gluUnProject not working
- C++ catch bad_alloc not working
- updatelayeredwindow not working
- OpenMP set_num_threads() is not working
- glOrtho not working
- Cuda atomicInc not working