Function in C does not return the number squared that the user computed

Asked

Viewed 52 times

0

I’m learning C and data structure, I’m using a workbook (https://docs.google.com/viewerng/viewer?url=https://api.apostilando.com/pdf-Viewer.php? pdf%3D3353_structure_data.pdf), I think I’m having problems in this workbook or I’m not understanding the content very well, because this is the 2nd algorithm that I try to do and does not match the workbook...

Algorithm

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

main() {

    int num;
    printf("Digite um numero: ");
    scanf("%d",&num);
    sqr(num); /*sqr recebe “num” do programa principal*/
}

    sqr() {
        int x;/* x é um “parâmetro” recebido do programa principal
              no caso x “vale” o conteúdo de num */
        printf("%d ao quadrado e: %d", x, x*x);
    }

The problem is that it does not return the number that the user placed and neither it squared, by the way, until it returns more the expected result does not come out as it should.

Upshot

Digite um numero: 10
4214871 ao quadrado e: 1152810385
Process returned 0 (0x0)   execution time : 1.278 s
Press any key to continue.

Edit: I had already made an algorithm that had not worked out and had posted here (Values in C do not return what is expected)

Edit2: I found another booklet in C, it’s good? (http://www.joinville.udesc.br/portal/professores/fiorese/materiais/apostilaC_Univ_Fed_Uberlandia.pdf), my only fear is she doesn’t portray too much background on data structure.

PS: If you can recommend some data structure booklet for my C learning to start with other languages, I would like to thank you.

1 answer

2


You are passing the number by parameter:

sqr(num);

But its function sqr does not have the parameter, it is like this:

void sqr () { ... }

And it should be like this:

void sqr (int x) { ... }

The value that appears in your result is the value of x that you created inside sqr, where you created but did not assign any value:

    void sqr() {
        int x; 

        /* esse X não está recebendo nenhum valor */

        printf("%d ao quadrado e: %d", x, x*x);
    }
  • It worked out! Thanks Thiago, but they had not mentioned anything of the void in the booklet... as you can see on page 39/152... Besides, I wanted to know if there is any other booklet that recommends me, because this one seems to be half incomplete.

  • @The code of this booklet is doubtful because it also generates a Warning in the function statement main(). Link to the corrected Code

  • @Augustovasques have any that recommend me? Not to generate long discussions, just send the link of the apostille (the).

  • 2

    http://www.joinville.udesc.br/portal/professores/fiorese/materiais/apostilaC_Univ_Fed_Uberlandia.pdf

  • Sorry man. I’ve never read a booklet in my life, but I recommend the book C For Dummies.

Browser other questions tagged

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