Question
This code in C only outputs as 0.00000 What changes need to be made to have it output more than just 0.000000 as an answer
This code in C only outputs as 0.00000
What changes need to be made to have it output more than just 0.000000 as an answer without changing the structure of the code.
#include
float s_exp(float sub_exp, char op); // function declaration
char get_op(); // function declaration
float get_num(); // function declaration
float m_exp(float sub_exp, char op); // function declaration
int main(void)
{
char cont = 'Y';
while (cont == 'Y' || cont == 'y') //while result equals y, the main program runs
{
printf("Enter an arithmetic expression: ");
float result = s_exp(get_num(),get_op()); // call function for simple expression and set it equal to result
printf(" The result is %f ", result);
printf("Do you want to continue? Y/N ");
scanf("%c",&cont);
//to satisfy while loop at the beggining, enter y to continue
}
}
float s_exp(float sub_exp, char op)
{
// create an if else setup and if * or / are found for the operators call the m_exp function because those take higher precidence in a bedmas calculation
if (op == ' ')
return sub_exp;
else if (op == '+')
return s_exp(sub_exp + get_num(), get_op());
else if (op == '-')
return s_exp(sub_exp - get_num(), get_op());
else if (op == '*')
return m_exp(sub_exp * get_num(), get_op());
else if (op == '/')
return m_exp(sub_exp / get_num(), get_op());
else
//if nothing is found thats / * + or - the operator is invalid and exit the program
{
printf("This expression is invalid. ");
return 0;
}
}
//m_exp takes higher precidence for the * or / operators. store those operators and return to sub_exp when a space, + or - is found. this is set through else if.
float m_exp(float sub_exp, char op) {
float f1;
char ch1;
if (op == ' ')
return sub_exp;
else if (op == '+')
return s_exp(sub_exp + get_num(), get_op());
else if (op == '-')
return s_exp(sub_exp - get_num(), get_op());
else if (op == '*'){
f1 =get_num();
ch1 = get_op();
}
else if (op == '/'){
f1 = get_num();
ch1 = get_op();
}
else
{
printf("This expression is invalid. ");
return 0;
}
return m_exp(f1, ch1);
}
// this if for assistance with the first two functions, this gathers the next operator in the expression.
char get_op()
{
char op = ' ';
while (op == ' ')
scanf("%c", &op);
return op;
}
// this if for assistance with the first two functions, this gathers the next number in the expression.
float get_num()
{
float num;
scanf("%f", &num);
return num;
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started