return string in a function

2

eg income 20weight, and 1.80 height, you get imc < 18.50. and I want to return the assigned string in overweight in the function. to say in console, 'You are overweight'.

#include <stdio.h>
char calculoimc(float peso, float altura)
{
    char sobre_peso='Estas sobre peso';
    char estado_salud;
    float imc=0;
    imc = peso/(altura*altura);
    if(imc < 18.50){
        estado_salud=sobre_peso;

    return estado_salud;
            }

}
int main(){
    float p,a;
    printf("Introduzca su peso: ");
    scanf("%f",&p);
    printf("Introduzca su altura: ");
    scanf("%f",&a);

    printf("Su estado es: %s",calculoimc(p,a));
}
    
asked by JGUser 03.04.2018 в 23:06
source

2 answers

2

The data type char is a character, not an array of characters or a string that is the same, so to represent that data you must use a pointer to char or a string, this is the first case:

char* calculoimc(float peso, float altura)
{
    char* sobre_peso='Estas sobre peso';
    char* estado_salud = '';
    float imc=0;
    imc = peso/(altura*altura);
    if(imc < 18.50){
        estado_salud=sobre_peso;    
    }
    return estado_salud;
}
    
answered by 03.04.2018 / 23:29
source
2

There are several inconsistencies in the code. In C the strings are treated as arrays (vectors) and you can not assign an array to another variable easily with a "=". Nor can you return an array with "return", this will return the memory address of the array (operations with pointers). Finally you have a "Warning" at the end of the execution because the main function you put int(main) so you must return an integer. In that case the usual thing is to put a return 0 at the end.

I would rewrite the code as follows:

#include <stdio.h>
float calculoimc(float peso, float altura)
{
    float imc=0.0;
    imc = peso/(altura*altura);
    return imc;
}

int main(){
    float p, a, imc;
    char bajo_peso[] = "Estas bajo de peso";
    char sobre_peso[] = "Estas sobre peso";
    char buen_peso[] = "Estas en el peso correcto";

    printf("Introduzca su peso (kg): ");
    scanf("%f",&p);
    printf("Introduzca su altura (m): ");
    scanf("%f",&a);

    imc = calculoimc(p,a);
    if(imc < 18.50) {
        printf("Su estado es: %s", bajo_peso);
    } else if(imc < 25.00) {
        printf("Su estado es: %s", buen_peso);
    } else {
        printf("Su estado es: %s", sobre_peso);
    }
    return 0;
}
    
answered by 03.04.2018 в 23:56