簡體   English   中英

為什么strtof總是在評估HUGE_VAL?

[英]why is strtof is always evaluating to HUGE_VAL?

這可能是什么問題? 無論我選擇什么數字為str,它始終是2681561585988519419914804999641169225495873164118478675544712​​2887443528060147093953603748596333806855380063716372972101707507765623893139892867298012168192.00

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â

您正在構建什么平台? 你說的警告正在發出:

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

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

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

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

也許您忘記包含正確的標題?

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

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

生產:

2.600000

為了我...

鑒於您的警告,您應該嘗試添加-std = c99以從標頭中獲取C99標准定義。 默認情況下,它將假定返回值為int,然后嘗試將其轉換為float。 這顯然是錯的。 或者,您可以簡單地為strtof()提供您自己的正確聲明。

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

我在使用glibc 2.5的CentOS 5.5上遇到strtof()的問題,除非我使用-std = c99,但是strtod()工作得很好。

暫無
暫無

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

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