使用浮点数调用strtof
在我的本地计算机上正常运行,但在学校的服务器上,strtof始终返回0.000000
。我检查了errno
中是否存在任何内容,因为0应该表示错误,但它表示成功。有谁知道为什么会这样?
这是代码。
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("%f\n", strtof(argv[1],0));
return 0;
}
答案 0 :(得分:5)
简短版本:使用-std=gnu99
或-std=c99
进行编译。说明如下。
我在自己的盒子上复制了类似的“问题”。但是,当我尝试编译时:
# gcc -Wall -o float float.c
float.c: In function 'main':
float.c:6: warning: implicit declaration of function 'strtof'
float.c:6: warning: format '%f' expects type 'double', but argument 2 has type 'int'
所以我查看man
的{{1}}页面,并说:
strtof()
这意味着在包含SYNOPSIS
#include <stdlib.h>
double strtod(const char *nptr, char **endptr);
#define _XOPEN_SOURCE=600 /* or #define _ISOC99_SOURCE */
#include <stdlib.h>
float strtof(const char *nptr, char **endptr);
long double strtold(const char *nptr, char **endptr);
之前,其中一个值必须为#define
d。但是,我刚刚使用stdlib.h
进行了重新编译,并为我定义了其中一个并且它有效。
-std=gnu99
道德:总是用# gcc -std=gnu99 -Wall -o float float.c
# ./float 2.3
2.300000
编译。 ; - )
答案 1 :(得分:2)
您是否已将头部定义为strtof(stdlib.h),否则您可能会得到0.0,因为默认情况下,C中的未知函数被视为返回int。