Guys, I need feedback on my code. I just need to know if this is a good way to do this at a beginner level and if the stated problem relates to my code.
The Problem:
Here is the code:
#include <stdio.h>
#include <string.h>
#include <math.h>
int factorialSolver(int num);
int powerSolver(int base, int p);
//
double discriminant(int a, int b, int c);
double oneRoot(int a, int b, int c);
double root1(int a, int b, int c);
double root2(int a, int b, int c);
int main() {
char choice;
printf("\n");
do{
printf("\n");
printf("\nCHOOSE AN APP");
printf("\na. Power Solver, b. factorial Solver, c. Quadratic Solver, q. Quit");
printf("\nChoice: ");
fflush(stdin);
scanf("%c", &choice);
if(choice == 'a' || choice == 'A') {
int base, power;
printf("Enter base: ");
scanf("%d", &base);
printf("Enter power: ");
scanf("%d", &power);
printf("%d raise to the power of %d is: %d", base, power, powerSolver(base, power));
} else if(choice == 'b' || choice == 'B') {
int num;
printf("Enter a number: ");
scanf("%d", &num);
if(num > 0) {
printf("The factorial of %d is: %d", num, factorialSolver(num));
} else {
printf("Invalid Input");
}
} else if(choice == 'c' || choice == 'C') {
int a,b,c;
printf("Enter a: ");
scanf("%d", &a);
printf("Enter b: ");
scanf("%d", &b);
printf("Enter c: ");
scanf("%d", &c);
if(a==0 && b==0) {
printf("There is no solution");
} else if (discriminant(a,b,c) < 0) {
printf("There are no real roots");
} else if(a==0) {
printf("Root: %.2lf",oneRoot(a, b, c));
} else {
printf("Root1: %.2lf", root1(a,b,c));
printf("\nRoot2: %.2lf", root2(a,b,c));
}
}
} while(choice != 'q');
printf("YOU EXITED");
return 0;
}
//Power Solver
int powerSolver(int base, int p) {
int result;
result = pow(base, p);
return result;
}
//Factorial Solver
int factorialSolver(int num) {
int result=1;
for(int i=1; i <= num; i++) {
result *= i;
}
return result;
}
//Quadratic Solver
double discriminant(int a, int b, int c) {
double answer;
answer = b * b - 4 * a * c;
return answer;
}
double oneRoot(int a, int b, int c) {
double answer;
answer = (-b / (double)c);
return answer;
}
double root1(int a, int b, int c) {
double result;
result = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);
return result;
}
double root2(int a, int b, int c) {
double result;
result = (-b - sqrt(b * b - 4 * a * c)) / (2 * a);
return result;
}
Sample output:
I think I am wrong in the quadratic part because I can’t seem to know how to implement the solution using only the quadraticSolver() function. So I just decomposed it into 4 functions.