2010-06-02 108 views
4

這裏有什麼問題?不要緊,我選擇什麼號碼海峽,它始終是2681561585988519419914804999641169225495873164118478675544712​​2887443528060147093953603748596333806855380063716372972101707507765623893139892867298012168192.00爲什麼strtof總是評估爲HUGE_VAL?

char *str = "2.6"; 
printf("%f\n", strtof(str, (char**)NULL)); 
//prints 26815615859885194199148049996411692254958731641184786755447122887443528060147093953603748596333806855380063716372972101707507765623893139892867298012168192.00 

整個程序:

#include <stdio.h> 
#include <string.h> 
#include <stdlib.h> 

int main(int argc, char *argv[]) 
{ 
    char *str = "2.6"; 
    printf("%f\n", strtof(str, NULL)); 
    return 1; 
} 

與-Wall編譯:

test4.c:7: warning: implicit declaration of function âstrtofâ 
+1

它在這裏工作正常;你在用一種不尋常的方式建設嗎? – 2010-06-02 17:33:12

+0

gcc -o test4 test4.c – user318747 2010-06-02 17:34:17

+0

嘗試'gcc -Wall' – 2010-06-02 17:36:10

回答

8

你建立什麼平臺/上?被釋放出來,你說的警告:

test4.c:7: warning: implicit declaration of function âstrtofâ 

表明,編譯器不知道strtof()返回一個浮點數,所以它要的int推到printf()呼叫,而不是一個doublestrtof()通常在stdlib.h中聲明,您包括在內。但在C99之前它不是一個標準函數,因此確切的編譯器平臺(以及您正在使用的配置/選項)可能會影響它是否可用。

+1

您必須使用'-std = c99'來使用它,或切換到strtod – ShinTakezou 2010-06-02 18:28:38

3

也許你已經忘記了包括正確的標題?

#include <stdlib.h> 
#include <stdio.h> 

int main() { 
    printf("%f\n", strtof("2.6", NULL)); 
    return 0; 
} 

生產:

2.600000 

我...

4

strtof僅在C99中定義。可能是因爲默認GCC(-std=gnu89)僅包含少數C99功能,所以將選項-std=c99傳遞給編譯器將會修復它。

另一種選擇是使用C89-kosher strtod。無論如何,從長遠來看,這可能是更好的選擇。 (除特殊情況外,你什麼時候需要單身?)

3

鑑於您的警告,您應該嘗試添加-std = c99以從標題中獲取C99標準定義。默認情況下,它會假定返回值是一個int,然後嘗試將其轉換爲一個浮點數。這顯然是錯誤的。或者,您可以簡單地爲strtof()提供您自己的正確聲明。

2

正如其他人所說的,你需要-std = c99。但是你也可以使用strtod()這是字符串加倍,你不需要-std = c99。

我在使用glibc 2.5的CentOS 5.5上遇到了strtof()問題,除非我使用-std = c99,但strtod()完美地工作。

相關問題