Code:
#include <stdio.h>
#include <ctype.h>
char get_first(void);
char get_choice (void);
int main (void)
{
int choice;
double first,second,result;
char test[255];
while ((choice=get_choice())!='q')
{
switch(choice)
{
case 'a': printf ("Enter first number: ");
while (scanf("%lf",&first)!=1)
{
scanf("%s",test);
printf ("%s is not a number\n",test);
printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
while (getchar()!='\n');
}
printf ("\nEnter second number: ");
while (scanf("%lf",&second)!=1)
{
scanf("%s",test);
printf ("%s is not a number\n",test);
printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
while (getchar()!='\n');
}
result=first+second;
printf ("%.2lf + %.2lf = %.2lf\n",first,second,result);
break;
case 's': printf ("Enter first number: ");
while (scanf("%lf",&first)!=1)
{
scanf("%s",test);
printf ("%s is not a number\n",test);
printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
while (getchar()!='\n');
}
printf ("\nEnter second number: ");
while (scanf("%lf",&second)!=1)
{
scanf("%s",test);
printf ("%s is not a number\n",test);
printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
while (getchar()!='\n');
}
result=first-second;
printf ("%.2lf - %.2lf = %.2lf\n",first,second,result);
break;
case 'm': printf ("Enter first number: ");
while (scanf("%lf",&first)!=1)
{
scanf("%s",test);
printf ("%s is not a number\n",test);
printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
while (getchar()!='\n');
}
printf ("\nEnter second number: ");
while (scanf("%lf",&second)!=1)
{
scanf("%s",test);
printf ("%s is not a number\n",test);
printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
while (getchar()!='\n');
}
result=first*second;
printf ("%.2lf * %.2lf = %.2lf\n",first,second,result);
break;
case 'd': printf ("Enter first number: ");
while (scanf("%lf",&first)!=1)
{
scanf("%s",test);
printf ("%s is not a number\n",test);
printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
while (getchar()!='\n');
}
printf ("\nEnter second number: ");
while (scanf("%lf",&second)!=1)
{
scanf("%s",test);
printf ("%s is not a number\n",test);
printf ("Please enter a number, such as 2.5, -1.78E8, or 3: ");
while (getchar()!='\n');
}
result=first/second;
printf ("%.2lf / %.2lf = %.2lf\n",first,second,result);
break;
default: printf ("Program error!\n");
break;
}
}
printf ("Bye.");
return 0;
}
char get_choice(void)
{
int ch;
printf ("Enter the operation of your choice:\n");
printf ("a. add s. subtract\n");
printf ("m. multiply d. divide\n");
printf ("q. quit\n");
ch=get_first();
while (ch!='a' && ch!='s' && ch!='m' && ch!='d' && ch!='q')
{
printf ("Please respond with a, s, m, d or q.\n");
ch=get_first();
}
return (ch);
}
char get_first(void)
{
int ch;
ch=getchar();
if (isupper(ch))
{
ch=tolower(ch);
}
while (getchar()!='\n')
{
continue;
}
return ch;
}