gpt4 book ai didi

c - 为什么 strtof 不打印正确的 float ?

转载 作者:太空狗 更新时间:2023-10-29 15:02:10 25 4
gpt4 key购买 nike

#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);

发生的事情是,如果没有声明,编译器会将函数的返回类型默认为 int。由于函数实际上返回一个 float , float 被解释为(未转换为)整数,然后该整数被转换为 float 。

没有产生警告,大概是因为 -Wall 不在编译器选项中,和/或正在使用的 C 标准允许使用未声明的函数。

关于c - 为什么 strtof 不打印正确的 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29787890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com