Here's a basic example of how to make a simple calculator program in C:-
#include
#include
int main()
{
char operator;
double num1, num2, result;
printf ("Enter an operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two numbers: ");
scanf("%lf %lf", &num1, &num2);
switch(operator)
{
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
printf("Error: Invalid operator");
return 0;
}
printf("%.2lf %c %.2lf = %.2lf", num1, operator, num2, result);
getch();
return 0;
}
Explanation:
- We first include the standard input-output library stdio.h. In the main() function, we declare four variables: operator, num1, num2, and result.
- We prompt the user to enter an operator (+, -, *, /) using the printf() function and read the operator input from the user using the scanf() function.
- We prompt the user to enter two numbers using the printf() function and read the number inputs from the user using the scanf() function.
- We use a switch statement to perform the appropriate arithmetic operation based on the operator entered by the user. If the operator is invalid, we print an error message and return 1.
- We print the result using the printf() function.
- We return 0 to indicate successful program execution.
Note: This is a very basic example of a calculator program and doesn't include input validation or error handling for situations such as division by zero.
Tags:
make calculator in C
