gpt4 book ai didi

将 char* 转换为 float 或 double

转载 作者:太空狗 更新时间:2023-10-29 16:45:57 26 4
gpt4 key购买 nike

我有一个从文件中读入的值,并存储为 char*。该值是一个货币数字,#.##、##.## 或###.##。我想将 char* 转换为我可以在计算中使用的数字,我试过 atof 和 strtod,它们只给我垃圾数字。执行此操作的正确方法是什么,为什么我做错了?

这基本上就是我正在做的,只是从文件中读入了 char* 值。当我打印出 temp 和 ftemp 变量时,它们只是垃圾,巨大的负数。

另一个编辑:

我在 gcc 中运行这个

#include <stdio.h>
int main()
{
char *test = "12.11";
double temp = strtod(test,NULL);
float ftemp = atof(test);
printf("price: %f, %f",temp,ftemp);
return 0;

我的输出是价格:3344336.000000, 3344336.000000

编辑:这是我的代码

if(file != NULL)
{
char curLine [128];
while(fgets(curLine, sizeof curLine, file) != NULL)
{
tempVal = strtok(curLine,"|");
pairs[i].name= strdup(tempVal);
tempVal = strtok(NULL,"|");
pairs[i].value= strdup(tempVal);
++i;
}
fclose(file);
}

double temp = strtod(pairs[0].value,NULL);
float ftemp = atof(pairs[0].value);
printf("price: %d, %f",temp,ftemp);

我的输入文件是非常简单的名称,像这样的值对:

NAME|VALUE
NAME|VALUE
NAME|VALUE

值(value)是美元金额

已解决:谢谢大家,我使用的是 %d 而不是 %f,并且没有包含正确的 header 。

最佳答案

您缺少一个包含: #include <stdlib.h> , 所以 GCC 创建了一个 atof 的隐式声明和 atod ,导致垃圾值。

double 的格式说明符是 %f , 不是 %d (即整数)。

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

int main()
{
char *test = "12.11";
double temp = strtod(test,NULL);
float ftemp = atof(test);
printf("price: %f, %f",temp,ftemp);
return 0;
}
/* Output */
price: 12.110000, 12.110000

关于将 char* 转换为 float 或 double,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10605653/

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