Dimitri Dimitri - 1 year ago 292
C Question

C calculator if else

I want to make a simple C calculator only with "IF" and "IF ELSE" conditions and it don't let me choose an operator ("+, -, * or /"), just appear my last if condition.

#include <stdio.h>
int main(){
int num1, num2, total;
char oper;
printf("Introduza o primeiro numero: \n");
scanf("%d", &num1);
printf("Introduza o segundo numero: \n");
scanf("%d", &num2);
printf("Escolha a operacao que quer realizar!\n\n");
scanf("%c", &oper);
if(oper == '+'){
printf("O resultado e: %d", num1+num2);
else if(oper == '-'){
printf("O resultado e: %d", num1-num2);
else if(oper == '*'){
printf("O resultado e: %d", num1*num2);
printf("O resultado e: %d", num1/num2);

Answer Source

I avoid scanf() and its cousins. Here is a version of your calculator that uses fgets() for the input. It also uses double for the operands.

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

#define ISIZE   100      // arbitrarily large

int main(){
    double num1, num2;
    int oper;
    char inp[ISIZE+1] = "";

    printf("Introduza o primeiro numero: ");            // 1st operand
    fgets (inp, ISIZE, stdin);
    num1 = atof (inp);

    printf("Introduza o segundo numero: ");             // 2nd operand
    fgets (inp, ISIZE, stdin);
    num2 = atof (inp);

    printf("Escolha a operacao que quer realizar! ");   // operator
    fgets (inp, ISIZE, stdin);
    oper = inp[0];

    printf ("O resultado e: %f %c %f = ", num1, oper, num2);

    switch (oper) {
        case '+': printf("%f\n", num1+num2); break;
        case '-': printf("%f\n", num1-num2); break;
        case '*': printf("%f\n", num1*num2); break;
        case '/': if (num2!=0) printf("%f\n", num1/num2);
                  else printf ("Divisão por zero!\n");
        default:  printf("Eu não sei o que operador\n");
    return 0;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download