2

如何将所有 4 个字符转换为浮点数?我只能将第一个字符转换为整数。你能否在你的解释中给我一些例子。谢谢

这是我到目前为止所尝试的。

void use_atof()
{

        char c[200];
        float val, v;

        strcpy(c ,"23.56,55.697,47.38,87.68");
        val = atof(c);
        printf("%f\n", val);
}
4

1 回答 1

3

您需要分离输入并在每个值上调用 atof()。

下面是使用 strtok 执行此操作的简单方法。请注意,它确实会破坏输入数据(添加 NULL),因此如果不可接受,您需要复制它或找到其他方式(例如,使用 strchr())。

void use_atof()
{

    char c[200];
    float val, v;
    char *ptr;

    strcpy(c ,"23.56,55.697,47.38,87.68");
    ptr = strtok(c,",");
    while (ptr) {
        val = atof(ptr);
        printf("%f\n", val);
        ptr = strtok(NULL,",");
    }
}

编辑:

根据请求,整个程序(在 Linux 上测试):

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

void use_atof(void);

int main()
{
    use_atof();
    exit (0);
}


void use_atof()
{

    char c[200];
    float val, v;
    char *ptr;

    strcpy(c ,"23.56,55.697,47.38,87.68");
    ptr = strtok(c,",");
    while (ptr) {
        val = atof(ptr);
        printf("%f\n", val);
        ptr = strtok(NULL,",");
    }
}
于 2016-01-11T06:16:27.757 回答