[英]Why does strtof always output 0.0000?
Calling strtof
with a floating point number runs fine on my local machine but on the school's servers strtof always returns 0.000000
. 在我的本地计算机上,使用浮点数调用
strtof
可以正常运行,但在学校的服务器上strtof始终返回0.000000
。 I checked to see if there was anything stored in errno
since a 0 should mean an error, but it says success. 我检查了一下是否在
errno
存储了什么,因为0意味着错误,但是它表示成功。 Does anyone have an idea why this might be? 有谁知道为什么会这样?
Here is the code. 这是代码。
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("%f\n", strtof(argv[1],0));
return 0;
}
Short version: compile with -std=gnu99
or -std=c99
. 简短版本:使用
-std=gnu99
或-std=c99
编译。 Explanation follows. 解释如下。
I've reproduced a similar "problem" on my own box. 我在自己的盒子上重现了类似的“问题”。 However, when I try to compile:
但是,当我尝试编译时:
# 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'
So I looked at the man
page for strtof()
, and it says: 所以我看了
man
页的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);
What that means is that one of those values has to be #define
d before including stdlib.h
. 这意味着在包含
stdlib.h
之前,这些值之一必须是#define
d。 However, I just recompiled with -std=gnu99
, and that defines one of those for me and it works. 但是,我只是重新编译了
-std=gnu99
,它为我定义了其中之一,并且可以工作。
# gcc -std=gnu99 -Wall -o float float.c
# ./float 2.3
2.300000
Moral: always compile with -Wall
. 道德:始终使用
-Wall
编译。 ;-) ;-)
是否已在定义strtof的标头中包含该标头(stdlib.h),否则可能会得到0.0,因为默认情况下,C中的未知函数被视为返回int。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.