Easy to creating a Simple calculator in C.
Here’s a simple calculator program in C that performs basic operations such as addition, subtraction, multiplication, and division:
c
#include <stdio.h> int main() { char operator; double num1, num2, result; // Input operator from the user printf("Enter an operator (+, -, *, /): "); scanf("%c", &operator); // Input two numbers from the user printf("Enter two numbers: "); scanf("%lf %lf", &num1, &num2); // Perform the operation based on the operator switch (operator) { case '+': result = num1 + num2; printf("%.2lf + %.2lf = %.2lf\n", num1, num2, result); break; case '-': result = num1 - num2; printf("%.2lf - %.2lf = %.2lf\n", num1, num2, result); break; case '*': result = num1 * num2; printf("%.2lf * %.2lf = %.2lf\n", num1, num2, result); break; case '/': if (num2 != 0) { result = num1 / num2; printf("%.2lf / %.2lf = %.2lf\n", num1, num2, result); } else { printf("Error: Division by zero is not allowed.\n"); } break; default: printf("Error: Invalid operator.\n"); } return 0; }
Explanation:
1. The program asks the user to input an operator (+
, -
, *
, /
).
2. The user is then prompted to input two numbers.
3. Based on the operator provided, the program calculates the result and displays it.
4. For division, the program checks if the divisor is zero to prevent division by zero errors.
Example Output:
c result
Enter an operator (+, -, *, /): + Enter two numbers: 5 10 5.00 + 10.00 = 15.00
Popular post
-
Eclipse IDE – Create New Java Project.
Opening the New Java Project…
-
How to start the project in android studio
Android Studio Open the Android…
-
How to use ACOSH function in excel
The ACOSH function returns the…
-
Complete Header tags in html – easy to learn
H tags can be used…
-
Best features in Python programme – easy to learn
Python is the most widely…