从string转换为float

时间:2015-10-19 03:20:44

标签: c casting

我正在尝试将变量从string转换为float。但我错了价值观。以下是我的代码。

#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给出正确的值,但我需要它以浮动格式。

1 个答案:

答案 0 :(得分:1)

您应该在此使用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