gpt4 book ai didi

从字符串转换为 float

转载 作者:行者123 更新时间:2023-11-30 15:16:09 27 4
gpt4 key购买 nike

我正在尝试将变量从字符串转换为 float 。但我得到了错误的值(value)观。下面是我的代码。

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

main(int argc,char *argv[])
{
char endTime[4][26];
time_t timere;
struct tm *tm_infoe;
float dlay[4][3];
time(&timere);
tm_infoe = localtime(&timere);
strftime(endTime[1], 26, "%Y%m%d%H%M%S", tm_infoe);
printf("Endtime %s\n", endTime[1]);
dlay[1][1]=atol(endTime[1]);
printf("Value from atol:%ld\n", atol(endTime[1]));
dlay[1][1]=atof(endTime[1]);
printf("Float value from atof:%f\n", dlay[1][1]);
sscanf(endTime[1], "%f", &dlay[1][1]);
printf("Float value from sscanf:%f\n", dlay[1][1]);
}

函数 atof 和 sscanf 都给出错误的值。下面是输出。你能告诉我错误在哪里吗?

Endtime 20151018221710
Value from atol:20151018221710
Float value from atof:20151017668608.000000
Float value from sscanf:20151017668608.000000

atol 给出了正确的值,但我需要浮点格式。

最佳答案

您应该在这里使用double而不是float。当您使用float时,许多数字可能会略有变化。因此,你得到这样的值,但并没有错。

这是一个使用double的简单示例 -

#include <stdio.h>
int main(void){
char s[]="20151018221710"; // your string
double a; // declare a as double
sscanf(s,"%lf",&a); // use %lf specifier for double
printf("%f",a); //print value of a
return 0;
}

输出 -

20151018221710.000000

Demo here

关于从字符串转换为 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33206130/

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