Calculator in C (Beginner)

Asked

Viewed 471 times

-3

I have a question in the following exercise:

Create a program that takes two whole numbers and shows the result of division of numbers and their rest. the program should ask if the user intends to repeat the operation or terminate the program.

I do not know how to do so that at the end of the program if I type 1, it closes, if type 2 again, follows below my program:

int main() 
{   
    int var1, var2, Q, R;
    printf("Digite o dividendo: ");
    scanf("%d", &var1);
    printf("Digite o divisor: ");
    scanf("%d", &var2);
    Q = var1 / var2;
    R = var1 % var2;
    printf("Resultado: %d\n", Q);
    printf("Resto: %d\n", R);

    int decisao;
    printf("\nDeseja encerrar o programa? \n1 para sim e 2 para nao.");
    scanf("%d", &decisao);
}
  • You’ve studied the command while? https://answall.com/questions/241665/la%C3%A7o-de-repeti%C3%A7%C3%A3o-em-c/241694

1 answer

2

You can use a repeat loop or at the end of your code, you can add a if to check if the value contained in the decision variable is equal to two, if the comparison result is true then you can call the method main() again.

Bow tie example Do While:

int main() 
{   
    int var1, var2, Q, R, decisao = 2;

    do {
        printf("Digite o dividendo: ");
        scanf("%d", &var1);
        printf("Digite o divisor: ");
        scanf("%d", &var2);
        Q = var1 / var2;
        R = var1 % var2;
        printf("Resultado: %d\n", Q);
        printf("Resto: %d\n", R);

        printf("\n Caso deseje repetir a operacao digite 2 ou digite qualquer outro valor para encerrar.\n");
        scanf("%d", &decisao);

    } while(decisao == 2);

}

Example with recursion:

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

int main() 
{   
    int var1, var2, Q, R;
    printf("Digite o dividendo: ");
    scanf("%d", &var1);
    printf("Digite o divisor: ");
    scanf("%d", &var2);
    Q = var1 / var2;
    R = var1 % var2;
    printf("Resultado: %d\n", Q);
    printf("Resto: %d\n", R);

    int decisao;
    printf("\n Caso deseje repetir a operacao digite 2 ou digite qualquer outro valor para encerrar.\n");
    scanf("%d", &decisao);

    if(decisao == 2)
        return main();  

}

inserir a descrição da imagem aqui

Note, I changed the message because the program will terminate to any value other than two.

  • 2

    Note to reader: Function recursion main is not the most common thing to find yourself out there. It’s usually something you avoid.

Browser other questions tagged

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