2010-06-02 170 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()完美地工作。

相关问题