为什么 strtof 不打印正确的浮点数?
Why does strtof not print proper float?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char aaa[35] = "1.25";
char* bbb = &(aaa[0]);
char** ccc = &(bbb);
float a = strtof(*ccc, ccc);
printf("%f\n", a);
return 0;
}
我上面写的代码应该打印1.25
,但是根据codepad(在线C编译器),它不打印1.25
。在键盘上,它打印 2097152.000000
。这是 codepad link
我做错了什么?
codepad 有一个旧版本的 gcc,大概是标准 C 库。显然, strtof
未由您包含的头文件声明。 (strtof
是在 C99 中添加的。)
尝试使用带有 postdiluvian 版本的 gcc 的在线服务。或者显式添加正确的声明:
float strtof(const char* ptr, char** end_ptr);
发生的事情是,如果没有声明,编译器会将函数的 return 类型默认为 int
。由于函数实际上 return 是一个浮点数,浮点数被解释为(未转换为)整数,然后该整数被转换为浮点数。
没有产生警告,大概是因为 -Wall 不在编译器选项中,and/or正在使用的 C 标准允许使用未声明的函数。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char aaa[35] = "1.25";
char* bbb = &(aaa[0]);
char** ccc = &(bbb);
float a = strtof(*ccc, ccc);
printf("%f\n", a);
return 0;
}
我上面写的代码应该打印1.25
,但是根据codepad(在线C编译器),它不打印1.25
。在键盘上,它打印 2097152.000000
。这是 codepad link
我做错了什么?
codepad 有一个旧版本的 gcc,大概是标准 C 库。显然, strtof
未由您包含的头文件声明。 (strtof
是在 C99 中添加的。)
尝试使用带有 postdiluvian 版本的 gcc 的在线服务。或者显式添加正确的声明:
float strtof(const char* ptr, char** end_ptr);
发生的事情是,如果没有声明,编译器会将函数的 return 类型默认为 int
。由于函数实际上 return 是一个浮点数,浮点数被解释为(未转换为)整数,然后该整数被转换为浮点数。
没有产生警告,大概是因为 -Wall 不在编译器选项中,and/or正在使用的 C 标准允许使用未声明的函数。