gpt4 book ai didi

将字符串中的数字转换为 c 中的 float : atof(), strtof() 不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 06:21:24 26 4
gpt4 key购买 nike

我的 C 生锈了。我正在尝试将字符串转换为 float (或 double )。我试过 atof() 和 strtof(),并尝试按照说明进行操作 herehere .运气不好。

这是我的代码:

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

int main(int argc, char *argv[]) {
float x;
char a[20];
strcpy(a,argv[1]);
x = strtof(a);
printf("%s\n",a);
printf("%f\n",x);
return 0;
}

运气不好。这是命令行上的输出:

prompt$ ./a.out 2.34
2.34
1426063.000000
prompt$

如果我改用 atoi(),我会得到 0.0。

显然我缺少一些简单的东西。这是在 ubuntu fwiw 上使用 gcc 4.8.4。

如果我使用 -static 标志编译,或者使用 double 代替 float(和 %e 代替 %f),或者包含 math.h,都没有区别。在某些情况下,输出会发生变化,但仍然是无意义的。

谢谢,彼得

最佳答案

您还没有包括 <stdlib.h>得到 strtof() 的原型(prototype)。所以返回类型默认为int。但是自 C99 以来,隐式 int 规则已从 C 中删除。

用法也不对。至少应该是:

char *eptr;

x = strtof(a, &eptr);

并检查 eptr对于转换失败。

编译时启用警告。 GCC 警告:

warning: implicit declaration of function ‘strtof’ [-Wimplicit-function-declaration]

关于将字符串中的数字转换为 c 中的 float : atof(), strtof() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34188066/

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