【问题标题】:character array to floating point conversion字符数组到浮点数的转换
【发布时间】:2013-03-28 01:00:24
【问题描述】:

我正在尝试转换输出缓冲区(字符数组) 将下面的代码转换为浮点格式以供进一步计算。 谁能告诉我怎么做。

#include "usbtmc.h"
#include <errno.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <getopt.h>
#include <inttypes.h>
#include <sys/types.h>
#include <pthread.h>

int main() 
{

    int myfile;
    char buffer[4000];

    int actual;

    myfile=open("/dev/usbtmc1",O_RDWR);
    if(myfile>0)
    {
        system("echo MEAS:VOLT:AC?>/dev/usbtmc1");
        actual=read(myfile,buffer,4000);

        buffer[actual] = 0;
        printf("Response = \n %s\n",buffer);

        close(myfile);
    }


    return 0;
}

此代码的示例输出是

响应 = +1.29273072E-04

【问题讨论】:

标签: c unix type-conversion


【解决方案1】:

你可能有两种方式:

  1. 使用double atof(const char* str)

    float f;
    f = (float)atof(buffer);
    printf("%f",f); // here you can use f
    
  2. 使用int sscanf( const char * s, const char * format, ...)

    float f;
    sscanf(buffer,"%f",&f);
    printf("%f",f); // here you can use f
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-03
    • 2014-02-22
    • 1970-01-01
    • 2019-06-22
    • 2016-06-14
    • 2010-10-23
    • 2017-09-28
    相关资源
    最近更新 更多