简体   繁体   中英

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 . I checked to see if there was anything stored in errno since a 0 should mean an error, but it says success. 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 . 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:

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 . However, I just recompiled with -std=gnu99 , and that defines one of those for me and it works.

# gcc -std=gnu99 -Wall -o float float.c
# ./float 2.3
2.300000

Moral: always compile with -Wall . ;-)

是否已在定义strtof的标头中包含该标头(stdlib.h),否则可能会得到0.0,因为默认情况下,C中的未知函数被视为返回int。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM