简体   繁体   English

在C的子程序中将float转换为字符串

[英]Converting a float to string in a subroutine in C

I am attempting to make a program in c where I use a subroutine to process some variables in a subroutine and return them as an array. 我试图在c中创建一个程序,在其中使用子例程来处理子例程中的某些变量并将它们作为数组返回。 For instance I have the numbers 2.5 and 3.5 and the subroutine multiplies these numbers by a certain value and then returns them as a string containing the two values. 例如,我有数字2.5和3.5,并且子例程将这些数字乘以某个值,然后将其作为包含两个值的字符串返回。

Below is the program I am trying to use: 以下是我尝试使用的程序:

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

char test_subroutine(float x,float y)
{
    float a=105.252342562324;
    float b=108.252234256262;
    float d;
    float e;
    char var;

    d=x*a;
    e=y*b;

    sprintf(var,"%0.2f %0.2f",d,e);

    return var;
}



int main()
{
    char variable;
    variable=test_subroutine(2.5,3.5);

}

When trying to compile I get the following error: 尝试编译时出现以下错误:

testrun.c: In function ‘char test_subroutine(float, float)’:
testrun.c:21:31: error: invalid conversion from ‘char’ to ‘char*’    [-fpermissive]
sprintf(var,"%0.2f %0.2f",d,e);
                           ^
In file included from testrun.c:1:0:
/usr/include/stdio.h:364:12: error:   initializing argument 1 of ‘int sprintf(char*, const char*, ...)’ [-fpermissive]
extern int sprintf (char *__restrict __s,

How do I resolve this issue? 我该如何解决这个问题?

You're trying to use sprintf to write data to a char . 您正在尝试使用sprintf将数据写入char Look at the declaration of the sprintf function, as your compiler suggests: 查看编译器建议的sprintf函数的声明:

int sprintf(char*, const char*, ...)

It takes a char* as first argument, that is: a pointer to a buffer where to store the formatted string that is generated. 它以char*作为第一个参数,即:一个指向缓冲区的指针,该缓冲区用于存储生成的格式化字符串。

You should use it like this (please pay attention to all the changes I made): 您应该这样使用它(请注意我所做的所有更改):

// Return the allocated buffer, which is char*, not char.
char *test_subroutine(float x,float y)
{
    float a=105.252342562324;
    float b=108.252234256262;
    float d;
    float e;

    char *var = malloc(100); // Allocate a buffer of the needed size.

    d=x*a;
    e=y*b;

    sprintf(var,"%0.2f %0.2f",d,e); // Sprintf to that buffer

    return var;
}



int main()
{
    char *variable;
    variable = test_subroutine(2.5,3.5);
    free(variable); // Free the buffer allocated by test_subroutine()
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM