簡體   English   中英

為什么strtof總是輸出0.0000?

[英]Why does strtof always output 0.0000?

在我的本地計算機上,使用浮點數調用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;
}

簡短版本:使用-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頁的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);

這意味着在包含stdlib.h之前,這些值之一必須是#define d。 但是,我只是重新編譯了-std=gnu99 ,它為我定義了其中之一,並且可以工作。

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

道德:始終使用-Wall編譯。 ;-)

是否已在定義strtof的標頭中包含該標頭(stdlib.h),否則可能會得到0.0,因為默認情況下,C中的未知函數被視為返回int。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM