我需要传递浮点数并在程序中获取它。
我尝试了几种方法,但没有成功。这是我的代码:
#include <stdio.h>
int main (int argc, char *argv[])
{
if(argc>1)
{
printf("String \t[%s]\n", argv[1] ); // 222
float floatNumber = atof( argv[1] );
printf("Float \t[%lf]\n", floatNumber ); //0.000000
printf("Float \t[%f]\n", floatNumber ); //0.000000
double doubleValue = atof( argv[1] );
printf("Double \t[%f]\n", doubleValue ); //0.000000
}
return 0;
}
答案 0 :(得分:7)
您需要#include <stdlib.h>
。
atof()
的函数原型在<stdlib.h>
中声明。如果未包含此结果,则假定atof()
函数返回int
。
如果您打开了编译器警告,您就会知道。例如,gcc给出以下警告:
warning: implicit declaration of function ‘atof’ [-Wimplicit-function-declaration]
答案 1 :(得分:2)
你应该添加头文件stdlib.h
和atof
返回double类型而不是float,所以试试这个:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main (int argc, char *argv[])
{
if(argc>1)
{
printf("%s\n", argv[1] ); // 222
double floatNumber = atof( argv[1] );
printf("%lf\n", floatNumber ); //0.000000
}
return 0;
}
此外,atof()
适用于c99 or c89:
zookeepdeMacBook-Pro:Desktop zookeep$ gcc test.c -o test
zookeepdeMacBook-Pro:Desktop zookeep$ ./test 222
222
222.000000
会正常工作。
答案 2 :(得分:-1)
首先包括stdlib.h
,然后更改此
printf("%lf\n", floatNumber );
到
printf("%f\n", floatNumber );
float
中printf()
的正确说明符为"%f"
。
通过省略stdlib.h
,编译器会假定atof()
返回int
,这是问题的原因。
您还应该使用一个允许您确保正确执行转换的函数,而不是假设argv[1]
是可转换的,因此,例如,将检查转换错误的程序版本将是
#include <stdlib.h>
#include <stdio.h>
int main (int argc, char *argv[])
{
if(argc>1)
{
char *endptr;
printf("%s\n", argv[1] ); // 222
float floatNumber = strtof(argv[1], &endptr);
if (*endptr != '\0')
printf("%s is not convertible to float\n", argv[1]);
else
printf("%f\n", floatNumber ); //0.000000
}
return 0;
}
最后:为了防止出现这种问题,使用编译器警告,编译器应该警告你隐式函数声明,因为atof()
是在你的程序中隐式声明的。
当隐式声明函数时,编译器假定它的返回值为int
。