I finished this code a few minutes ago. It started off as an explanation of a basic calculator in C to a friend. Then we decided to take it further and I made this. Please tell me where I can make changes, no matter how small, you think needs to be changed/made better. Also I'm new to the C language, I've self studied it for around 4-5 months.
I did not get any errors and it works exactly like I expected it to. I am just looking for help improving myself and the way I code. Also this is my biggest code in C yet.
And please feel free to share your own similar calculators or creations.
Code:
#include <stdio.h>
#include <math.h>
#define pi 3.14159265359
float add(float a, float b);
float sub(float a, float b);
float mult(float a, float b);
float divide(float a, float b);
float sqroot(float a);
float power(float a, float b);
float sine(float a);
float cosine(float a);
float tangent(float a);
float logarithm(float a);
int main() {
float a, b, val;
int op;
char choice;
printf("to choose an operation, enter the number of the operation 1)+ 2)- 3)* 4)/ 5)power 6)sqrt 7)sin 8)cos 9)tan 10)log(base 10) : ");
scanf("%d", &op);
if (op > 0 && op < 6) {
printf("enter first number: ");
scanf("%f", &a);
printf("enter second number: ");
scanf("%f", &b);
}
else if (op > 5 && op < 11) {
printf("enter a number: ");
scanf("%f", &a);
}
switch(op) {
case 1: val = add(a, b); break;
case 2: val = sub(a, b); break;
case 3: val = mult(a, b); break;
case 4: val = divide(a, b); break;
case 5: val = power(a, b); break;
case 6: val = sqroot(a); break;
case 7: val = sine(a); break;
case 8: val = cosine(a); break;
case 9: val = tangent(a); break;
case 10: val = logarithm(a); break;
default: printf("invalid operator..."); break;
}
if (op > 0 && op < 11) {
printf("answer is: %f", val);
getchar();
printf("\ncontinue? (y/n) ");
scanf("%c", &choice);
if (choice == 'y') {
main();
}
else if (choice == 'n') {
printf("ok cool bye");
}
}
return 0;
}
float add(float a, float b) {
return a + b;
}
float sub(float a, float b) {
return a - b;
}
float mult(float a, float b) {
return a * b;
}
float divide(float a, float b) {
return a / b;
}
float sqroot(float a) {
return sqrt(a);
}
float power(float a, float b) {
return pow(a, b);
}
float sine(float a) {
return sin(a * pi / 180);
}
float cosine(float a) {
return cos(a * pi / 180);
}
float tangent(float a) {
return tan(a * pi / 180);
}
float logarithm(float a) {
return log10(a);
}
/*if (op == '+') {
printf("\n %f + %f = %f", a, b, a + b);
}
else if (op == '-') {
printf("\na - b = %f", a - b);
}
else if (op == '-' && a < b) {
printf("\nb - a = %f", b - a);
}
else if (op == '*') {
printf("\na * b = %f", a * b);
}
else if (op == '/') {
printf("\na / b = %f", a / b);
}*/