我想将一个变量从字符串转换为浮点数。但我得到错误的价值。以下是我的代码。从字符串转换为浮点数
#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给出正确的值,但我需要它在浮动格式。
它是如何错了吗?它不会变好。 – deviantfan
'float'精确到7-8位十进制数字。看起来你在这个容忍度内观察结果。这又是什么问题? –