Hello. I am new to programming in C an found this forum. I need some help with a program that receives user input, does a mathematical calculation and outputs the result. The program consists of rules such as no use of string handling functions, no arrays or no global variables.
For example, the user enters:
9+8, the output should be 9+8=17
9 + 9, the output should be 9+9=18
*9, output should be error
2 1/3, output should be an error because there should not be a space between 2 and 1
6 % 3, output should be 6%3=0
9 -, output should be an error.
I'm having a few problems, but the major ones are:
1) I am using a global variable for the operator value. I have tried creating a function to handle this and I am receiving a '0' value for the operator, thus receiving a result of '0' when I try to implement the function.
2) The program doesn't evaluate and expression like:
9 - 9
Entering this expression will output an Error message when it shouldn't.
3) After entering an expression such as:
*9
Error.
Please enter an equation for evaluation
3+8
at this point the output will read
9+3=12
Would you like to continue? Y or N: y
The program will close.
My code (with global variable) is as follows:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
int Convert(char);
char Oper = '/0';
int Operator(char);
int main(void){
int Num1=0;
int Num2=0;
char answer='y';
// char Oper='/0';
char ch;
int Result=0;
do{
printf("Please enter an equation for evaluation.\n");
while(((ch=getchar())!=EOF)&&(ch!='\n')){
if((ch==' ')||(ch=='\t')){
ch='/0';
continue;
}
else if(!isdigit(ch)){
ch=0;
printf("Error.\n");
break;
}
else if(isdigit(ch)){
Num1=Convert(ch);
}
ch=getchar();
if(isdigit(ch)){
Num2=Convert(ch);
}
else if(!isdigit(ch)&&(ch=='\n')){
ch=0;
printf("Error4.\n");
break;
// ch=getchar();
// putchar(ch);
}
else if(!isdigit(ch)&&(ch!=EOF)){
continue;
}
if(Oper=='+')
Result=Num1+Num2;
else if(Oper=='-')
Result=Num1-Num2;
else if(Oper=='*')
Result=Num1*Num2;
else if(Oper=='/')
Result=Num1/Num2;
else if(Oper=='%')
Result=Num1%Num2;
printf("%d%c%d=%d\n",Num1, Oper, Num2, Result);
printf("Would you like to continue? Y or N:");
scanf ("%c%*c", &answer);
if(answer=='n'||answer=='N'){
printf("Thanks. Goodbye.");
exit(1);
}
}
}while((answer=='y')||(answer=='Y'));
return 0;
}
int Convert(char c){
int ch;
int sum=c-'0';
// char Operand='/0';
while(((ch=getchar())!=' ')&&(ch!='\n')){
if(!isdigit(ch)){
Oper=ch;
if(ch==' '||ch=='/t')
ch='/0';
break;
}
sum=sum*10+(ch-'0');
//printf("Error9.");
}
return sum;
}
//int Operator(char c){
// char Oper='/0';
// if(c=='+')
// Oper='+';
// else if(c=='-')
// Oper='-';
// else if(c=='*')
// Oper='*';
// else if(c=='/')
// Oper='/';
// else if(c=='%')
// Oper='%';
// return Oper;
//
//}
If someone can help please.