How to do operations between functions in C?

1

The funA() function stores a value entered by the user. The funB() function will allow the user to choose an option. My difficulty is in the third function: I need to create a function that multiplies the value stored in the first function by the value generated by the user's choice. I do not know how to call these functions within function C and use the stored values.

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

void funA(){

    int numA;
    scanf("%d", &numA);
}


void funB(){
    int numB;
    float x;

    printf("Escolha um valor:\n");
    printf("1 - Alto\n");
    printf("2 - Medio\n");
    printf("3 - Baixo\n");

    scanf("%d", &numB);

    if(numB == 1){x = 100;}
    if(numB == 2){x = 50;}
    if(numB == 3){x = 10;}

}
void funC(){
//?????
}
    
asked by anonymous 28.09.2015 / 20:00

2 answers

3

You have two functions, funcA() and funcB() independent, everything that happens inside them ceases to exist when they finish executing. You can do two things:

1) Make them return something using return (consequently they can not be void )

Eg:

int funA(){
    int numA;
    scanf("%d", &numA);
    return numA;
}

float funB(){
    int numB;
    float x;

    printf("Escolha um valor:\n");
    printf("1 - Alto\n");
    printf("2 - Medio\n");
    printf("3 - Baixo\n");

    scanf("%d", &numB);

    if(numB == 1){x = 100;}
    if(numB == 2){x = 50;}
    if(numB == 3){x = 10;}

    return x;
}

void funC(){
    int a = funcA();
    float b = funcB();
    float c = a + b;
    printf("Resultado: %.2f", c);
}

2) Sending as a parameter to both the pointer to variables created in funcC() , or global variables, if you have them. For this, study pointers and passing parameters by value and by reference.

    
28.09.2015 / 20:10
2

The variables in question exist only within their functions, they are local variables, and it is not possible to manipulate them from outside functions. To solve your problem there are two alternatives.

1. Declare the variables as global:

#include <stdio.h>

    int numA;
    float x;

    void funA(){

        scanf("%d", &numA);
    }


    void funB(){

        printf("Escolha um valor:\n");
        printf("1 - Alto\n");
        printf("2 - Medio\n");
        printf("3 - Baixo\n");

        scanf("%d", &numB);

        if(numB == 1){x = 100;}
        if(numB == 2){x = 50;}
        if(numB == 3){x = 10;}

    }

    void funC(){

        printf("%f", x * numA);
    }

2. Or change the return type of the functions and manipulate them:

#include <stdio.h>

int funA(){
    int numA;

    scanf("%d", &numA);
    return numA;
}


float funB(){
    int numB;
    float x;

    printf("Escolha um valor:\n");
    printf("1 - Alto\n");
    printf("2 - Medio\n");
    printf("3 - Baixo\n");

    scanf("%d", &numB);

    if(numB == 1){x = 100;}
    if(numB == 2){x = 50;}
    if(numB == 3){x = 10;}
    return x;

}
void funC(){
    printf("%f", funA() * funB());
}
    
28.09.2015 / 20:11