Write a simple calculator program in C

 #include <stdio.h>


int main() {

    char operator;

    double num1, num2, result;


    printf("Enter an operator (+, -, *, /): ");

    scanf("%c", &operator);


    printf("Enter two operands: ");

    scanf("%lf %lf", &num1, &num2);


    switch(operator) {

        case '+':

            result = num1 + num2;

            printf("%.2lf + %.2lf = %.2lf", num1, num2, result);

            break;


        case '-':

            result = num1 - num2;

            printf("%.2lf - %.2lf = %.2lf", num1, num2, result);

            break;


        case '*':

            result = num1 * num2;

            printf("%.2lf * %.2lf = %.2lf", num1, num2, result);

            break;


        case '/':

            if (num2 == 0) {

                printf("Error: divide by zero");

            } else {

                result = num1 / num2;

                printf("%.2lf / %.2lf = %.2lf", num1, num2, result);

            }

            break;


        default:

            printf("Error: invalid operator");

            break;

    }


    return 0;

}

In this program, we declare four variables: operator to hold the operator, num1 and num2 to hold the operands, and result to hold the result of the calculation. We prompt the user to enter an operator and read it in using scanf.

We then prompt the user to enter two operands and read them in using scanf. We use a switch statement to perform the appropriate calculation based on the operator entered. We handle the case of division by zero as a special case.

Finally, we print out the result of the calculation using printf, formatted to two decimal places. If there is an error, such as an invalid operator, we print an error message instead.

The program returns 0 to indicate successful execution.

Post a Comment

0 Comments