Functions and procedures in Portugol

Asked

Viewed 1,132 times

0

About functions and procedures, I have a big doubt in this matter.

I know that a function will always return data and that procedure has no return, but every function has to fill in all parameters? I wonder why my code is not working, the sum of the numbers always comes to zero.

What’s the matter?

programa
{
    funcao inicio(){
        inteiro resultado = 0, n1=0, n2=0
        escreve()
        
        escreva(somar(n1,n2))
    }

    funcao escreve(){
        inteiro n1, n2
        escreva("Digite n1 ")
        leia(n1)
        escreva("Digite n2 ")
        leia(n2)    
    }

    funcao inteiro somar(inteiro a, inteiro b){
        retorne a + b
    }
}
  • 1

    Well, your job is escreve type reads and forgets. In function you declare two variables: n1 and n2, with scope restricted to the function, then you read values for each of these variables, but there closes the function, ie read values are lost. Note that in its function inicio you declare the variables n1 and n2 with initial value 0 and therefore the function call somar(n1,n2) return 0, regardless of what was read in escreve. Study on the scope of variables.

2 answers

1

Observing your code, n1 and n2, in function escreve, are local variables and are not changing the value of n1 and n2 declared in function inicio. That is, when the program runs, even if you assign value to n1 and n2 (required by the function escreve), the value being passed as function parameter soma is actually the n1 and n2 of function inicio, that have not been changed and therefore still stand at zero. Hence their sum results in zero.

I found the function escreve unnecessary and put the development of it within the function inicio, according to the following code. In this case, I believe it is necessary to pass parameters.

função somar(inteiro a, inteiro b){
    int res;

    res = a+b;
    retorne res;
}

funcao inicio{
    int resultado = 0, n1=0, n2=0;

    escreva ("Digite n1: ");
    leia (n1);
    escreva("Digite n2: ");
    leia ("%i", &n2);

    escreva("A soma dos numeros é: ", resultado = somar(n1,n2)); 
}

0


From what I understand from your code, we’re missing a variable to return the sum response.

program {

  variavel 
     int n1, n2, resp


  escreva 
   ("Digite n1: ")
  leia n1
  escreva 
    ("Digite n2:  ")
   leia n2

   resp = (n1 + n2)

   escreva 
    ("O resultado é igual á:  " , resp)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.